linuxawk

What is the meaning of array index [fp+0] in awk example?


At this page https://www.gnu.org/software/gawk/manual/html_node/More-CSV.html, have this example to work on awk with csv files.

The example works very well!

But, I couldn't understand the fpat+0 on this code:

BEGIN {
     fp[0] = "([^,]+)|(\"[^\"]+\")"
     fp[1] = "([^,]*)|(\"[^\"]+\")"
     fp[2] = "([^,]*)|(\"([^\"]|\"\")+\")"
     FPAT = fp[fpat+0]
}

What that means?


Solution

  • From OP's link we see how the gawk script is called:

    $ gawk -v fpat=2 -f test-csv.awk sample.csv
    

    What happens if user provides no -v fpat=... clause?

    In (g)awk adding a zero to an undefined variable (eg, fpat+0) will generate a 0:

    $ awk 'BEGIN {print fpat+0}'
    0
    

    Regarding the referenced gawk code, when fpat+0 generates a 0 we end up using fp[0] as the default pattern.