如何在条件下使用多个模式

时间:2017-05-08 10:10:28

标签: json linux parsing awk

test.txt文件中的输入文本:

{"col1":"250000","col2":"8089389","col4":"09876545","col3":"121","col5":"123456789"}
{"col1":"210000","col3":"112","col2":"8089389","col4":"09876545","col5":"123456789"}
{"col1":"120000","col2":"8089389","col3":"123","col4":"09876545","col5":"123456789"}
{"col1":"170000","col2":"8089389","col4":"09876545","col5":"123456789","col3":"123"}
{"col1":"190000","col2":"8089389","col4":"09876545","col5":"123456789,"col3":"124""}
{"col3":"176","col1":"220000","col2":"8089389","col4":"09876545","col5":"123456789"}

我尝试的命令行和结果:

$ awk -F"," '{for(i=1;i<=NF;i++){ if($i ~ /col1/){print $i} };for (x=1;x<=NF;x++){if($x ~ /col3/){print $x}}}' test.txt
{"col1":"250000"
"col3":"121"
{"col1":"210000"
"col3":"112"
{"col1":"120000"
"col3":"123"
{"col1":"170000"
"col3":"123"
{"col1":"190000"
"col3":"124"
{"col1":"220000"
"col3":"176"

我想得到的预期结果:

col1:250000,col3:121
col1:210000,col3:112
col1:120000,col3:123
col1:170000,col3:123
col1:190000,col3:124
col1:220000,col3:176

2 个答案:

答案 0 :(得分:2)

好像在解析 _context.AwsmAppusers.Attach(User); _context.Remove(User); _context.SaveChanges(); 文件。您可以使用json

jq

了解更多信息:jq manual

答案 1 :(得分:1)

如果缺少json工具,则此处为awk黑客

$ awk -F'[:,]' -v OFS=, -v cols='col1,col3' '
       {n=split(cols,c); 
        gsub(/[{}"]/,""); 
        for(i=1;i<NF;i+=2) a[$i]=$(i+1); 
        for(i=1;i<=n;i++) printf "%s%s", (c[i]":"a[c[i]]), (i==n?ORS:OFS)}' file

col1:250000,col3:121
col1:210000,col3:112
col1:120000,col3:123
col1:170000,col3:123
col1:190000,col3:124
col1:220000,col3:176