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
?
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityhead -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.
head -7
is going to give you lines 1-7, not just line 7.sed -n 7p
.sed -n -e '7p'
(orsed -n -e '7p;7q'
) to print the 7th line; it uses fewer processes. Usinghead -n 7
prints 7 lines; if you only want the seventh, thentail -n 1
prints the last. The advantage of thesed
command is that it works more economically when you want line 7654321 instead of line 7. The variant with7q
quits after the 7th line; that may generate a SIGPIPE to the process feeding the data to the command sequence. The variant without7q
reads all the input, avoiding SIGPIPE signals. Most commands don't care and stop on SIGPIPE; some are noisy.