Reputation: 17553
Is there a way to print the nth line of a file, counting from the back of the file?
I know how to do it from the front of the file, but doing it from the back of the file seems to be more tricky.
Upvotes: 6
Views: 5689
Reputation: 56069
The quick and easy way is tail -n $n file | head -n 1
.
A more fun way with awk
is:
awk -v n=$n '{x[NR%n]=$0}END{print x[(NR+1)%n]}' file
If you have fewer than n
lines, the tail | head
method will print the first line of the file, the awk
way will print a blank line.
Upvotes: 12
Reputation: 88378
Quick and dirty, 100th line from the end:
tail -n 100 yourfile | head -n 1
You'll get the first line of the file if it has less than 100 lines.
Upvotes: 5