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

62k views Asked by At

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.

6

There are 6 answers

2
ennuikiller On BEST ANSWER
head -2 myownfile | tail -1 

should do what you want

0
Fred Foo On

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

0
user3287432 On

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
0
bodo On

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.

0
Sean On

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

0
Abhijit On

tail -2 myownfile.txt|head -1

it will show the 2nd line.