2017-04-24 17 views
0

我有日誌行像無法從AWK

{"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} 

我要在以下格式

123,400,2016-01-04T09:26:26.743Z 

我想出了這個

cat test.log| grep "Result For Test Id" | awk '{split($0,a,","); print a[5] a[6] }' 
輸出脫身所需格式

這是給出的輸出

"msg":"Result For Test Id 123 : 400""time":"2016-01-04T09:26:26.743Z" 

我無法從中得到輸出。

請幫忙。

謝謝

回答

1

您可以只用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的

+0

感謝您的回答和解釋 –

0

命令是:

cat test.log | grep "Result For Test Id" | awk -F "," '{print $5,$6}' | awk -F "\"" '{print $4,$8}' | awk -F " " '{print $5","$7","$8}' 

結果:

123,400,2016-01-04T09:26:26.743Z 
+0

GNU awk(幾乎可用於所有現代Linux發行版)支持多字符作爲分隔符。你不需要所有這些管道。通過定義分隔符爲','或''''或'space',您可以執行'awk -F「[,\」]「'{print $ 24」,'$ 26「,」$ 31}「。 –