Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to print the nth line from the end of a file in bash?

Tags:

bash

sed

tail

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.

like image 812
user788171 Avatar asked Nov 17 '13 23:11

user788171


People also ask

How do I print the nth line in Linux?

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.

How do I print the end of a line in bash?

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.


1 Answers

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.

like image 138
Kevin Avatar answered Sep 19 '22 00:09

Kevin