您可以只用sed的正則表達式的擴展支持(-r或-E開關)和正則表達式組:
$ a=$'{"name":"Test","ip":"ip-ip-ip-ip","pid":30536,"level":30,"msg":"Result For Test Id 123 : 400","time":"2016-01-04T09:26:26.743Z","v":1}'
$ sed -r 's/(.*Test Id)(.[^:]*)(:)(.[^"]*)(.*time":")(.[^"]*)(.*)/\2,\4,\6/g' <<<"$a" #replace <<<"$a" with 'yourfile' (without <<<)
# Output:
123,400,2016-01-04T09:26:26.743Z
正則表達式說明:
Basic sed usage ----> s/oldvalue/newvalue/ : Substitutes oldvalue with newvalue
Group 1 (.*Test Id) ----> Match everything from beginning up to: 'Test Id + space'
Group 2 (.[^:]*) ----> next, match everything that follows Test Id excluding ':' => up to first found ':' => matches '123'
Group 3 (:) ----> next, match 'space:space'
Group 4 (.[^"]*) ----> next, match all chars exluding '"' => up to first found '"' => matches '400'
Group 5 (.*time":") ----> next, matches all chars up to: 'time":"'
Group 6 (.[^"]*) ----> next match whatever follows previous group up to first " ==> 2016-01-04T09:26:26.743Z
Group 7 (.*) ----> next match all the rest chars
/\2,\4,\6/g ----> replace the whole input/original stream with regex groups 2,4 and 6. midifier 'g' in the end means global replacements.
Offcourse相似操作可以在gnu awk中完成:
awk '{match($0,/(.*Test Id)(.[^:]*)(:)(.[^"]*)(.*time":")(.[^"]*)(.*)/,f);print f[2]","f[4]","f[6]}' <<<"$a"
AWK的匹配功能,分割線($ 0)成片/正則表達式組,每個組的結果被存儲在數組f的
感謝您的回答和解釋 –