The need to get/print a particular line of a file on the Linux shell is a common task. Luckily there are various ways to do this. Below are three great ways to get the nth line of a file in Linux.

1. head / tail

Simply using the combination of the head and tail commands is probably the easiest approach. Below is an example using head and tail to read the 25th line of sample_data_1.txt:

cat sample_data_1.txt | head -25 | tail -1

2. sed

There are a couple of nice ways to do this with sed. The first is with the p (print) command, and the other is with the d (delete) command. The n option with the print command is used to only print lines explicitly indicated by the command. For example, sed will output the 25th line of sample_data_1.txt with each of the commands below:

#print/p command
cat sample_data_1.txt | sed -n '25p'

#delete/d command
cat sample_data_1.txt | sed '25!d'

3. awk

awk has a built in variable NR that keeps track of file/stream row numbers. awk syntax and idioms can be hard to read, so below are three different ways to print line 25 of sample_data_1.txt file using awk.

#awk example 1
cat sample_data_1.txt | awk 'NR==25'
#awk example 2
cat sample_data_1.txt | awk 'NR==25{print}'
#awk example 3
cat sample_data_1.txt | awk '{if(NR==25) print}'

Leave a Reply

3 ways to get the Nth Line of a File in Linux