Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash tool to get nth line from a file

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.

like image 855
Vlad Vivdovitch Avatar asked May 16 '11 19:05

Vlad Vivdovitch


People also ask

How do I print the nth line in bash?

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.

How do you get a specific line from a file Linux?

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.


1 Answers

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 
like image 80
anubhava Avatar answered Oct 09 '22 18:10

anubhava