如何使用awk获取键值对?

时间:2016-11-11 12:29:34

标签: shell awk

我的txt文件的值为

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之外的任何东西。

修改

OUTPUT就像:

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

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

1 个答案:

答案 0 :(得分: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的值。这就是你的问题的编辑部分似乎表明你想要完成的事情;如果没有,希望它至少会指出你正确的方向。

相关问题