Using combination of "head" and "tail" to display middle line of the file in Unix

55,965

Solution 1

head -2 myownfile | tail -1 

should do what you want

Solution 2

head -2 displays first 2 lines of a file

$ head -2 myownfile.txt
foo
hello world

tail -1 displays last line of a file:

$ head -2 myownfile.txt | tail -1
hello world

Solution 3

I'm a bit late to the party here, but a more flexible way of doing this would be to use awk rather than using head and tail.

Your command would look like this:

awk 'NR==2' myfile.txt

hello world

Solution 4

Try head -2 | tail -1. That's the last line (tail -1) of the first half + one (head -2).

Solution 5

tail -2 myownfile.txt|head -1

it will show the 2nd line.

Share:
55,965
Ali
Author by

Ali

Working at CDOT on Mozilla @Webmaker. Passionate about the web. A Strong believer in an open source projects and a Mozillian https://mozillians.org/en-US/u/aali/

Updated on July 05, 2022

Comments

  • Ali
    Ali almost 2 years

    If I have a file name myownfile.txt which contains 3 lines of text.

    foo
    hello world
    bar
    

    I want to display the line in the middle which is hello world by using head and tail command only.

  • Ali
    Ali over 12 years
    Thank you it does work! can you give a little bit of explaination please about the part where head says -2 means start from line 2? and tail -1 also start from line 2 from bottom?
  • Ali
    Ali over 12 years
    Thank you for the explanation it helps me a lots
  • ADTC
    ADTC over 10 years
    head -2 gets the first two lines of the file. This output is piped to tail -1 which gets the last one line of the piped output (this might be somewhere in the middle of the file).