19

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.

Adrian Heine
  • 4,051
  • 2
  • 30
  • 43
Ali
  • 9,997
  • 20
  • 70
  • 105

6 Answers6

27
head -2 myownfile | tail -1 

should do what you want

ennuikiller
  • 46,381
  • 14
  • 112
  • 137
  • 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 Nov 01 '11 at 19:32
  • 2
    `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). – ADTC Nov 19 '13 at 02:59
5

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
Maxime Lorant
  • 34,607
  • 19
  • 87
  • 97
user3287432
  • 51
  • 1
  • 1
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

Ganton
  • 208
  • 2
  • 10
Sean
  • 31
  • 1
1

tail -2 myownfile.txt|head -1

it will show the 2nd line.

Abhijit
  • 11
  • 2
1

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

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
0

There have been a few instances in the past, where someone provided a daring solution to some file handling problem with sed. I never really understood how they worked.

Today I had to do some line editing on huge files with just the basic tools and came across this question. Not satisfied by using combinations of tail and head I decided to find out about the true power of sed.

Reading https://www.grymoire.com/Unix/Sed.html gave me all the information I needed. So I want to share this with anybody else who might stumble upon a similar problem and not know the true power of sed:

sed -n "2 p" myownfile.txt

The -n option disables all implicit printing, 2 addresses just the second line and p prints that specific line to stdout.

bodo
  • 1,005
  • 15
  • 31