Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWK -Print the next to last field of each line of input file

Tags:

field

awk

I have an input file file the content of which constantly is updated with various number of fields, what I am trying to is to print out to a new file the next to last field of each line of input file: awk '{print $(NF-1)}' outputfile

error: and awk: (FILENAME=- FNR=2) fatal: attempt to access field -1

Need help. Thanks in advance

like image 337
Zerg12 Avatar asked Mar 27 '13 02:03

Zerg12


2 Answers

On lines with no fields (blank lines, or all whitespace) NF is 0, so that evaluates to $(-1). Also if there's only one field your code will print $0 which may not be what you want.

awk 'NF>=2 {print $(NF-1)}'
like image 71
John Kugelman Avatar answered Nov 10 '22 11:11

John Kugelman


Should be awk 'NF > 1 { print $(NF - 1); }'

awk 'NF { print $(NF - 1) }' is not correct. When NF == 1 it'll print $0 which is not next to the last field.

like image 31
pynexj Avatar answered Nov 10 '22 11:11

pynexj