Another.Chemist
Another.Chemist

Reputation: 2559

AWK, fatal: attempt to access field -1

Good day,

I was wondering how to make awk correctly printing the structure of the input file when I'm trying to use awk 'BEGIN { FS = "," } ; NF > 1 {print $(NF-1)}'.

Expected output

bogota
bogota
bogota
bogota
bogota



whitehouse stn

With the proposed attempt, I obtain:

bogota
bogota
bogota
bogota
bogota
whitehouse stn

And, if I don't use NF > 1, I get the error mentioned on this post title.

Thanks in advance for any clue

Upvotes: 1

Views: 4398

Answers (2)

Ed Morton
Ed Morton

Reputation: 203995

awk -F, '{print $(NF>1?NF-1:"")}' file

Upvotes: 2

rici
rici

Reputation: 241861

If I understand your needs correctly, you want:

awk -F, '{print $(NF?NF-1:0)}'

That will print the second last field if there are two or more fields, and otherwise the entire line.

Explanation:

The expression inside the parentheses is the standard ?: ternary operator, which has the form condition ? value_if_true : value_if_false. In awk, a numeric value (like NF) is true if it is not 0.

It also important to know that in awk, the $ is a unary operator taking a numeric argument. $(i) is the ith field if 0 < i ≤ NF; the entire line if i == 0; and an empty string if i > NF. Other values of i are illegal.

Upvotes: 3

Related Questions