2016-11-11 48 views
-1

我已经txt文件与下面的值如何使用awk获取键值对?

f:0 
c:Test C 
s:test S 
ctype:0 
a:test A 
t:10 
r:test r 

f:0 
c:Test C1 
s:test S1 
ctype:1 
a:test A1 
t:10 
r:test r 

f:20 
c:Test C 
s:test S 
ctype:2 
a:test A1 
t:0 
r:test r 

我曾尝试下面的代码,但它是不是给所有单个新行的值作为键值对环双新行适当的输出:

awk ' 
    BEGIN { 
    FS="\n" 
    RS="" 
} 
{ 
    print $1 "\n " $2 "\n" $3 
} 

可以使用awk以外的任何东西。

编辑:

输出会是这样:

if(ctype==0){ 
execute c; 
}else if(ctype==1){ execute a} 

我想循环中的数据并执行操作。

+0

'awk -F:'NF {print $ 1,$ 2}'file' – anubhava

+5

预期输出是什么? – user000001

+1

告诉我们一个命令不会做你想做的事,告诉我们它没有做你想做的事情,不会告诉我们你想做什么! –

回答

0

我不能完全肯定我明白你的问题,但是这是接近你心目中是什么:

{ 
    if (/^a:/) a = substr($0, 3) 
    if (/^c:/) c = substr($0, 3) 
    if (/^ctype:/) ctype = substr($0, 7) 
    if (/^$/) { 
     if (ctype == "0") { 
      print "a: [", a, "]" 
     } else { 
      print "c: [", c, "]" 
     } 
    } 
} 
END { 
    if (ctype == "0") { 
     print "a: [", a, "]" 
    } else { 
     print "c: [", c, "]" 
    } 
} 

这读取测试的每个块,寻找A,C和CTYPE的值,然后根据ctype的值打印a或c的值。这就是你的问题的编辑部分似乎表明你想要完成;如果没有,希望它至少能指引你朝着正确的方向前进。