我有像
这样的日志行{"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"
我无法从中获得输出。
请帮忙。
谢谢
答案 0 :(得分: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.
可以在gnu awk中进行类似的操作:
awk '{match($0,/(.*Test Id )(.[^:]*)( : )(.[^"]*)(.*time":")(.[^"]*)(.*)/,f);print f[2]","f[4]","f[6]}' <<<"$a"
匹配awk函数,将行($ 0)拆分为片段/正则表达式组,每个组的结果存储在数组f
答案 1 :(得分: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