do not read first line of file in awk command file

无人久伴 提交于 2019-12-23 19:33:57

问题


I am having trouble making it so that my list of awk commands does not read the first line of a data file. It must read each line except for the first, and then concatenate the athlete and year into a string. Later in the program I use an array, I did not list all of the code. The first two lines of the data file are listed below. I need to make it so it does not read the heading line and only starts with the first athlete. Any help on this would be great!

Script:

BEGIN{
FS=","
cnt=0; sum=0;
}
{
name=$1
year=$4
ayStr = name "," " " year

回答1:


Use NR > 1 before the block that processes the file lines:

BEGIN {
FS=","
cnt=0; sum=0;
}
NR > 1 {
name=$1
year=$4
ayStr = name "," " " year

NR is the line number in the file, so it only processes lines after 1




回答2:


As @Barmar mentions you can test NR>1 to skip the first line but why skip it when you can use it? Do this instead and you don't need to hard-code the field numbers in your script, just access them by the value they have on the first line:

$ cat tst.awk
BEGIN{ FS="," }

NR==1 {
    for (i=1;i<=NF;i++) {
        f[$i] = i
    }
    next
}

{
    ayStr = $(f["Athlete"]) ", " $(f["Year"])
    print ayStr

    print "----"

    for (name in f) {
        value = $(f[name])
        print name " = " value
    }
}

.

$ awk -f tst.awk file
Yannick Agnel, 2012
----
Silver Medals = 1
Total Medals = 3
Athlete = Yannick Agnel
Gold Medals = 2
Closing Ceremony Date = 8/12/2012
Year = 2012
Age = 20
Bronze Medals = 0
Sport = Swimming
Country = France


来源:https://stackoverflow.com/questions/27388723/do-not-read-first-line-of-file-in-awk-command-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!