Vim

替換一個字元串

  • October 15, 2021

我有一些這種格式的字元串:

"User-Password":"aaaa","Calling-Station-Id":"bbbb","Eltex-AVPair":"cccc","h323-call-type":"dddd","Framed-IP-Address":"eeee","NAS-IP-Address":"ffff","Cisco-AVPair":["xpgk-request-type=gggg","xpgk-src-number-in=hhhh","xpgk-dst-number-in=iiii","xpgk-src-number-out=jjjj","xpgk-dst-number-out=kkkk","h323-gw-address=llll"],"Acct-Session-Id":"mmmm","User-Name":"nnnn","Called-Station-Id":"oooo","h323-gw-id":"pppp","Event-Timestamp":"qqqq","h323-conf-id":"rrrr","h323-call-origin":"ssss","NAS-Port-Type":"tttt","NAS-Port":"uuuu"

我需要將其轉換為

User-Password = "aaaa"
Calling-Station-Id = "bbbb"
Eltex-AVPair = "cccc"
h323-call-type = "dddd"
Framed-IP-Address = "eeee"
NAS-IP-Address = "ffff"
Cisco-AVPair = "xpgk-request-type=gggg"
Cisco-AVPair = "xpgk-src-number-in=hhhh"
Cisco-AVPair = "xpgk-dst-number-in=iiii"
Cisco-AVPair = "xpgk-src-number-out=jjjj"
Cisco-AVPair = "xpgk-dst-number-out=kkkk"
Cisco-AVPair = "h323-gw-address=llll"
Acct-Session-Id = "mmmm"
User-Name = "nnnn"
Called-Station-Id = "oooo"
h323-gw-id = "pppp"
Event-Timestamp = "qqqq"
h323-conf-id = "rrrr"
h323-call-origin = "ssss"
NAS-Port-Type = "tttt"
NAS-Port = "uuuu"

使用 vim。

所以應該是這樣的

:s/\,/\r/g|:s/^\"//g|(something_for_copying_Cisco-AVPair)|:s/\"\:/\ \=\ /g 

它分為四個部分:

  1. 將 , 轉換成 \r
  2. 刪除^"
  3. 複製 Cisco-AVPair 並刪除方括號
  4. 將 ‘":’ 轉換為 ’ = '

我只能寫這些替換的第一部分和最後一部分。我該如何與他人相處?

您可以進行一系列搜尋/替換。

:%s/,/\r/g
:%s/^"
:v/:/s/^/Cisco-AVPair":"
:%s/\v":\[?"/ \= "

這轉化為

  1. ,用換行符替換每個
  2. 刪除所有前導引號
  3. 將不包含 a的行的開頭替換:Cisco-AVPair":"
  4. 全部替換":["= "

我找到了這個任務的下一個解決方案:

echo '' | jq -r 'paths(scalars) as $p|[([$p[]|tostring ]|join(".->.") ),(getpath($p)|tojson)]|join(" = ")'|grep '^RAD_REQUEST\.\-'|sed -r 's/^[A-Z_]+\.\->\.//'|sed -r 's/\.\->\.[0-9]+//'

您應該在引號之間輸入請求以使其工作

引用自:https://unix.stackexchange.com/questions/638364