Zerg12
Zerg12

Reputation: 317

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

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

Upvotes: 6

Views: 15568

Answers (2)

Kent
Kent

Reputation: 195039

another awk line: (golfing a bit):

awk 'NF>1&&$0=$(NF-1)' 

Upvotes: -1

John Kugelman
John Kugelman

Reputation: 361585

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)}'

Upvotes: 12

Related Questions