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 myscript.py
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!
$ awk 'FNR=42' myscript.py $ head -42 myscript.py | 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' myscript.py $ awk 'NR >= 5 && NR <= 42' myscript.py $ head -42 myscript.py | 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!