How to get 'Nth' line of a text file in linux

How to get 'nth' line of a text file in linux
How to get 'nth' line of a text file in linux

 Below are the two better ways to print nth line of text files in linux.

1. Use the combination of head and tail command

one of the easiest way of printing nth line of a text file is by using the combination of head and tail command.Below is an exapmle of how to use it for displaying the 9th line of a file named sample.txt


cat sample.txt | head -9 | tail -1


If you want to display 9th and 10th line replace the value of tail to 2 as below.


cat sample.txt | head -9 | tail -2


2. using sed command

There are two ways to do this with sed command. one is with one is with using p(print) and other is with using d(delete) along with sed command.

following are the examples


cat sample.txt | sed -n '9p'     .---> This will display the 9th line of sample.txt file

cat sample.txt | sed -n '9p;12p'      ---> This will display 9th and 12th line of  sample.txt

Like wise we can display as much of line of a file as per our need.


cat sample.txt | sed '9!d'   ---> This will display the 9th line of sample.txt

No comments:

Post a Comment