Is there a "canonical" way of doing that? I've been using head -n | tail -1
which does the trick, but I've been wondering if there's a Bash tool that specifically extracts a line (or a range of lines) from a file.
By "canonical" I mean a program whose main function is doing that.
N is the line number that you want. For example, tail -n+7 input. txt | head -1 will print the 7th line of the file. tail -n+N will print everything starting from line N , and head -1 will make it stop after one line.
Using the head and tail Commands The idea is: First, we get line 1 to X using the head command: head -n X input. Then, we pipe the result from the first step to the tail command to get the last line: head -n X input | tail -1.
head
and pipe with tail
will be slow for a huge file. I would suggest sed
like this:
sed 'NUMq;d' file
Where NUM
is the number of the line you want to print; so, for example, sed '10q;d' file
to print the 10th line of file
.
Explanation:
NUMq
will quit immediately when the line number is NUM
.
d
will delete the line instead of printing it; this is inhibited on the last line because the q
causes the rest of the script to be skipped when quitting.
If you have NUM
in a variable, you will want to use double quotes instead of single:
sed "${NUM}q;d" file
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With