awk数组在打印时改写自己

时间:2017-11-20 18:07:03

标签: arrays awk keyvaluepair

这是我的第一个问题,如果我错过任何内容,请告诉我。

这是一个awk脚本,它使用数组来创建键值对。

我有一个文件,其中包含以冒号分隔的标题信息。数据低于它并以冒号分隔。我的目标是创建打印到新文件的键值对。我已将所有设置都放在数组中,它几乎打印出

以下是输入:

...:iscsi_name:iscsi_alias:panel_name:enclosure_id:canister_id:enclosure_serial_number
...:iqn.1111-00.com.abc:2222.blah01.blah01node00::11BLAH00:::

以下是代码:

#!/bin/awk -f
BEGIN {
    FS = ":"
}
{
    x = 1
    if (NR==1) {
        num_fields = NF ###This is done incase there are uneven head fields to data fields###
        while (x <= num_fields) {
            head[x] = $x
            x++
        }
    }
    y = 2
    while (y <= NR) {
        if (NR==y) {
            x = 1
            while (x <= num_fields) {
                data[x] = $x
                x++
            }
            x = 1
            while (x <= num_fields) {
                print head[x]"="data[x]
                x++
            }
        }
        y++
    }
}
END {
    print "This is the end of the arrays and the beginning of the test"
    print head[16]
    print "I am head[16]-"head[16]"- and now I'm going to overwrite everything"
    print "I am data[16]-"data[16]"- and I will not overwrite everything, also there isn't any data in data[16]"
}

以下是输出:

...
iscsi_name=iqn.1111-00.com.abc
iscsi_alias=2222.blah01.blah01node00
panel_name=
enclosure_id=11BLAH00
canister_id=
=nclosure_serial_number ### Here is my issue ###
This is the end of the arrays and the beginning of the test
enclosure_serial_number
- and now I'm going to overwrite everything
I am data[16]-- and I will not overwrite everything, also there isn't any data in data[16]

注意:数据[16]不在一行的末尾,由于某种原因,数据行上有一个额外的冒号,因此上面的num_fields注释

为什么head [16]会覆盖自己?是否在该字段的末尾有换行符(\ n)?如果是这样,我该如何摆脱它?我试过添加减去最后一个字符,没有运气。我试图限制数组在该字段上可以接受的字符数,没有运气。我尝试过更多的想法,没有运气。 完全披露:我对所有这些都比较新,我可能搞砸了以前的这些修补程序!

有没有人知道为什么会这样? 谢谢! -cheezter88

1 个答案:

答案 0 :(得分:0)

您的脚本不必要地复杂。如果要使用第一行调整记录大小,请执行此操作。

(我用“x”代替“......”前缀)

awk -F: 'NR==1 {n=split($0,h); next}   # populate header fields and record size
         NR==2 {for(i=1;i<=n;i++)      # do the assignment up to header size
                  print h[i]"="$i}' file

x=x
iscsi_name=iqn.1111-00.com.abc
iscsi_alias=2222.blah01.blah01node00
panel_name=
enclosure_id=11BLAH00
canister_id=
enclosure_serial_number=

如果要对其余记录执行此操作,请删除NR==2条件