lanselibai
lanselibai

Reputation: 1273

How to obtain the value for the 3rd one from the bottom in bash?

I have a line like this

3672975 3672978 3672979

awk '{print $1}' will return the first number 3672975

If I still want the first number, but indicating it is the 3rd one from the bottom, how should I adjust awk '{print $-3}'?

The reason is, I have hundreds of numbers, and I always want to obtain the 3rd one from the bottom.

Can I use awk to obtain the total number of items first, then do the subtraction?

Upvotes: 0

Views: 50

Answers (2)

tso
tso

Reputation: 4934

or with cut and rev

echo 1 2 3 4 | rev | cut -d' ' -f 3 | rev
2

Upvotes: 1

James Brown
James Brown

Reputation: 37464

$NF is the last field, $(NF-1) is the one before the last etc., so:

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

for example:

$ echo 3672975 3672978 3672979 | awk '{print $(NF-2)}'
3672975

Edit:

$ echo 1 10 100 | awk '{print $(NF-2)}'
1

Upvotes: 2

Related Questions