awkの

2017-04-24 12 views
0

私は私がこのawkの

cat test.log| grep "Result For Test Id" | awk '{split($0,a,","); print a[5] a[6] }' 
が出ている

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

次の形式で出力したい

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

のようなログの行を持っていますから、必要な形式に出ることができません。

これは出力を与えています

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

私はこれから出力を得ることができません。

助けてください。

はありがとう

答えて

1
あなただけの拡張正規表現のサポート(-rまたは-Eスイッチ)と正規表現のグループとsedを使用することができ

$ 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の

match関数、片/正規表現グループにライン($ 0)分割し、各グループの結果はコマンドである

+0

答えと説明ありがとう –

0

Fアレイに記憶されている:

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ディストリビューションで利用可能)は、区切り文字としてマルチキャラクタをサポートしています。これらのパイプはすべて必要ありません。区切り文字を '、' '' ''、 ''スペース ''にすることで 'awk -F" [、\ "]" '{print $ 24 "、" $ 26 "、" $ 31} "とすることができます。 –