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.
N is the line number that you want. For example, tail -n+7 input. txt | head -1 will print the 7th line of the file. tail -n+N will print everything starting from line N , and head -1 will make it stop after one line.
Printing Newline in Bash The most common way is to use the echo command. However, the printf command also works fine. Using the backslash character for newline “\n” is the conventional way. However, it's also possible to denote newlines using the “$” sign.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With