To print a specific line from a file

awk 'FNR==5' <file>
Just one character longer than the sed version ('FNR==5' versus -n 5p). On my system, without using "exit" or "q", the awk version is over four times faster on a ~900K file using the following timing comparison: testfile="testfile"; for cmd in "awk 'FNR==20'" "sed -n '20p'"; do echo; echo $cmd; eval "$cmd $testfile"; for i in {1..3}; do time for j in {1..100}; do eval "$cmd $testfile" >/dev/null; done; done; done Adding "exit" or "q" made the difference between awk and sed negligible and produced a four-fold improvement over the awk timing without the "exit". For long files, an exit can speed things up: awk 'FNR==5{print;exit}' <file>

By: dennisw
2009-10-20 22:52:41

3 Alternatives + Submit Alt

What Others Think

This post helped me a lot in finding valuable information regarding the ways to print a specific line from a file. I have tried it out and it worked effectively. Do share more such an interesting post. eCommerce Clipping Path Services
Juvanta · 77 weeks and 4 days ago
Here in this post, it discusses the commands to print a specific line from a file. Here it also discusses the three alternatives to this Continue Reading command. This is the best place for students who love to learn such command line programming languages. Looking here for more details on that.
Alyssalauren · 28 weeks and 2 days ago

What do you think?

Any thoughts on this command? Does it work on your machine? Can you do the same thing with only 14 characters?

You must be signed in to comment.

What's this? is the place to record those command-line gems that you return to again and again. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.

Share Your Commands

Stay in the loop…

Follow the Tweets.

Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.


Subscribe to the feeds.

Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):

Subscribe to the feed for: