views:

63

answers:

5

What is the best way (better performance) to read a specific line of a file? Currently, I'm using the following command line:

head -line_number file_name | tail -1

ps.: preferentially, using shell tools.

+1  A: 

You could use sed.

# print line number 10
$ sed -n '10p' file_name
$ sed '10!d' file_name
$ sed '10q;d' file_name
The MYYN
On my system, your last example is generally faster than the awk, head/tail or ruby versions unless the line is near the end of the file. Only the tail/head version begins to get a little faster as the line approaches the end of the file.
Dennis Williamson
+1  A: 

awk -v linenum=10 'NR == linenum {print; exit}' file

glenn jackman
Could just use `awk NR==10 file_name` as in my answer.
dogbane
If the file is huge, you don't want to read the rest of it needlessly, so exit.
glenn jackman
A: 
ruby -ne '$.==10 and (print; exit)' file
`ruby -ne '$.==10 and (print; exit)'` will be faster.
Dennis Williamson
+1  A: 

If you know the lines are the same length, then a program could directly index in to that line without reading all the preceeding ones: something like od might be able to do that, or you could code it up in half a dozen lines in most-any language. Look for a function called seek() or fseek().

Otherwise, perhaps...

tail +N | head -1

...as this asks tail to skip to the Nth line, and there are less lines put needlessly through the pipe than with your head to tail solution.

Tony
That should be `head 1` instead of `head -1`.
Dennis Williamson
@Dennis: are you sure? With all the head implementations I've ever seen `head 1` would try to find a file called "1". I've double-checked on GNU/Linux and it's definitely `head -1`. Which version of head do you use?
Tony
Oh, sorry, GNU `head` insists on `-n` so `head -n 1`. I typoed my comment. With a `-n -1` GNU `head` outputs all but the last line rather than just the first. Version: head (GNU coreutils) 7.4
Dennis Williamson
A: 
#print 10th line
awk NR==10 file_name
dogbane