neorc
neorc

Reputation: 277

awk nth element before last

I tried to get the nth element before last in UNIX shell, "nth element" is stored in a variable.

I tried awk the followings, but none of them work.

awk '{print $NF-$minus_day}'
awk '{print $(NF-$minus_day)}'
awk '{print $(NF-minus_day)}'

Upvotes: 0

Views: 253

Answers (1)

fedorqui
fedorqui

Reputation: 289505

You cannot directly use a bash variable in awk, you have to pass it either with -v:

awk -v minus=$minus_day '{print $(NF-minus)}' file
    ^^^^^^^^^^^^^^^^^^^

or

awk '{print $(NF-minus)}' minus=$minus_day file
                          ^^^^^^^^^^^^^^^^

For a given input file:

$ cat file
one 2 3 4 5 6 7 8 9 10 11 12 13 14 15

It would return

$ minus_day=3
$ awk -v minus=$minus_day '{print $(NF-minus)}' file
12

$ minus_day=4
$ awk -v minus=$minus_day '{print $(NF-minus)}' file
11

Upvotes: 5

Related Questions