Unix - show the second line of the file

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 above command displays the data as follows: mark

But I can’t understand this, because head -2 is used to print the first two lines, and tail -1 prints the last line, but how does the second line get! ???

+8
unix
source share
3 answers

the tail displays the last line of the head output, and the last line of the head output is the second line of the file.

Head output (tail entry):

 hello mark 

Tail output:

 mark 
+8
source share

You can also use "sed" or "awk" to print a specific line:

Example:

 sed -n '2p' myfile 

PS: Regarding the β€œwhat's wrong with my team” head | tail "- the shelltel is correct.

+10
source share

If you break down operations into separate commands, it becomes obvious why it works the way it works.

head -2 creates a two-line file.

 linux> head -2 /tmp/x > /tmp/xx linux> cat /tmp/xx hello mark 

tail -1 displays the last line in the file.

 linux> tail -1 /tmp/xx mark 
+2
source share

All Articles