Reputation: 2938
this command displays the second line of the file :
cat myfile | head -2 | tail -1
My file contains the following data :
hello
mark
this is the head line
this is the first line
this is the second line
this is the last line
the command above prints the data as: mark
But i am unable to understand this because, head -2 is used to print the first two lines and tail -1 prints the last line but how come 2nd line is printed!!???
Upvotes: 41
Views: 120549
Reputation: 12767
You could use sed
command. Following are ways you could print the line number, you may select as per your task.
sed -n '2p' filename #get the 2nd line and prints the value (p stands for print)
sed -n '1,2p' filename #get the 1 to 2nd line and prints the values
sed -n '1p;2p;' filename #get the 1st and 2nd line values only
Upvotes: 5
Reputation: 1572
If you break up operations into separate commands, it will become obvious why it works the way it works.
head -2 creates a file of two lines.
linux> head -2 /tmp/x > /tmp/xx
linux> cat /tmp/xx
hello
mark
tail -1 prints out the last line in the file.
linux> tail -1 /tmp/xx
mark
Upvotes: 2
Reputation: 121649
You can also use "sed" or "awk" to print a specific line:
EXAMPLE:
sed -n '2p' myfile
PS: As to "what's wrong with my 'head|tail'" command - shelltel is correct.
Upvotes: 47
Reputation: 97948
tail displays the last line of the head output and the last line of the head output is the second line of the file.
Output of head (input to tail):
hello
mark
Output of tail:
mark
Upvotes: 22