Reputation: 1315
I need to print out a particular record, which is the 3d from the tail, that is NR == total NR-2. I've been trying to do that for almost an hour and still can't get it work, so this is what I have:
cat myfile | grep mystring | awk 'END {NR == $(NR-2); print $0}'
This gives me the last NR, why?
Upvotes: 0
Views: 1288
Reputation: 4623
There are 2 possibilities.
you can use the command tac (instead cat) to reverse the file (from tail to head) and print the 3rd
or use a buffer to put in memory the last x results
Upvotes: 0
Reputation: 56099
awk
processes each line and just throws it out when it's done, you have to save it manually [N.B. Your NR == $(NR-2)
checks whether the number of rows is equal to the (number of rows - 2)th field in the last row]. Easiest would be to store them all, but that's not very memory efficient so we can store just the last three we've seen. Actually the easiest would be to use head
and tail
:
grep mystring myfile | tail -n3 | head -n1
Or with awk
:
awk '/mystring/{three = two; two = one; one = $0} END{print three}' myfile
Upvotes: 2