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.
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.