Don't read the first line of a file in awk command file

I'm having trouble that my awk command list is not reading the first line of the data file. He must read every line except the first and then concatenate the athlete and year into a line. Later in the program I use an array, I didn't list all the code. The first two lines of the data file are listed below. I need to make it so that it doesn't read the title bar 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

      

+3


source to share


2 answers


Use NR > 1

before the block that processes the lines of the file:

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

+3


source


As @Barmar states, 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 have to hard-code the field numbers in the 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

      

+1


source







All Articles