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.

One thought on “3 ways to get the Nth Line of a File in Linux”

  1. TalkArtFunDay

    Couple of observations:
    1. first option does not guarantee to pick the 25th line, if the file had less than 25 lines. It will pick the last line which might be the 10th line, instead of showing a blank line.
    2. cat | construct is not usually needed with most unix commands. Instead just works. Certainly the case with head, sed, awk as:
    %head -25 sample_data_1.txt | tail -1
    %sed -n ’25p’ sample_data_1.txt
    %awk ‘NR==25’ sample_data_1.txt

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="">