Shell Foo: Printing the Nth Line of a File

You’re running a Python script from the command line, and it throws some exception in your face. You want to take a quick look at the line that raised the exception (say, 42). How would you print that line?

My favorite way (minimal typing):

$ sed -n 42p

Shell-Foo credit for this one: Eyal Fink.

Shell-Foo is a series of fun ways to take advantage of the powers of the shell. In the series, I highlight shell one-liners that I found useful or interesting. Most of the entries should work on bash on Linux, OS X and other UNIX-variants. Some probably work with other shells as well. Your mileage may vary.

Feel free to suggest your own Shell-Foo one-liners!

ShellFoo: Printing the Nth line of a file


$ awk 'FNR=42'
$ head -42 | tail -1

I heard claims that the awk variant is much faster than sed. Didn’t bother checking it out though.

Printing a range of lines?

What if I want to print lines 5..42?

$ sed -n '5,42p'
$ awk 'NR >= 5 && NR <= 42'
$ head -42 | tail -38

The head | tail is less elegant this time, as it requires calculating 42-5+1. Basic arithmetic, yuck.

Can you think of better methods? Got performance data? Share it in the comments!

  • Uriel guy
    November 20, 2014

    You can use tail -n+5 and save the calculations

Leave a Reply