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

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:

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:

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">