-1

I've noticed that people typically use head -n | tail -n 1 to find the nth line of a file in Shell.

For example, if I was asked to find the 7th line of a file, why not just use head -7 instead of creating pipelines with tail?

3
  • Well, head -7 is going to give you lines 1-7, not just line 7. Mar 13 at 18:54
  • The "better" way, which some people use, is sed -n 7p. Mar 13 at 18:55
  • 1
    It's better to use sed -n -e '7p' (or sed -n -e '7p;7q') to print the 7th line; it uses fewer processes. Using head -n 7 prints 7 lines; if you only want the seventh, then tail -n 1 prints the last. The advantage of the sed command is that it works more economically when you want line 7654321 instead of line 7. The variant with 7q quits after the 7th line; that may generate a SIGPIPE to the process feeding the data to the command sequence. The variant without 7q reads all the input, avoiding SIGPIPE signals. Most commands don't care and stop on SIGPIPE; some are noisy. Mar 13 at 18:55

1 Answer 1

5
head -7

Or its modern and standard equivalent:

head -n 7

prints the first 7 lines (or up to 7 if there are fewer) of the input.

piping that to tail -n 1 gets the last line out of those, so the 7th line only or the last line if there are fewer lines.

To get the 7th line only (and nothing if there are fewer lines), you'd use:

tail -n +7 | head -n 1

Which for large values or the line number would also be more efficient as less data goes through the pipe.

You could also do it in one sed command:

sed '7!d;q'

Though that's likely less efficient as sed is not as specialised as head and tail, and sed contrary to head/tail is not required to be able to deal with lines longer than LINE_MAX so depending on the implementation may not work on overly long lines.

Note that sed -n 7p or sed '7!d' as suggested in comments read the whole input even after the 7th line has been printed, rather than stop reading there like head does. That's less efficient, but in some cases like when applying to the output of a command which we do not want to terminate after its 7th line has been output, that might be preferable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy