Friday, December 28, 2007

Print Nth line of file : Unix

If you what to print nth line of a file

head -n filename tail -1

Result:
head -n filename will give the n lines to the buffer
This will be redirected to tail -1. So the last line from buffer will get

Example:

Filename : users.txt

1 Muthu
2 Anto
3 Murali
4 Sri
5 Hema
6 Subbu
7 Babu

head -5 users.txt tail -1

head -5 users.txt --

1 Muthu
2 Anto
3 Murali
4 Sri
5 Hema

From this buffer -- tail -1 will give the last line output

5 Hema

Submitted by Muthu

Other methods

Lazy method

head -n4 file > tmpfile1
head -n5 file > tmpfile2
diff tmpfile1 tmpfile2 > difference

awk

awk '{ if (NR==5) print $0 }' filename

sed

sed -n '5p' filename

2 comments:

Anonymous said...

It seems a pipe symbol is missing in the above line. It should look like.

head -n filename | tail -1

Anonymous said...

update hemaraj