1827831 Members
1928 Online
109969 Solutions
New Discussion

head / tail function

 
SOLVED
Go to solution
u856100
Frequent Advisor

head / tail function

people,

if I have a file thus :

1
2
3
4
5

and I wanted to get a section, or number of lines from the middle (using two line numbers) i.e. :

2
3
4

how would I do this (could I use head or tail?)

many thanks
John
chicken or egg first?
4 REPLIES 4
Ramkumar Devanathan
Honored Contributor
Solution

Re: head / tail function

suppose the numbers are as follows in a.txt -

1
2
3
4
5
.
.
.
10

#!/bin/bash

# expects number of lines to be removed from head and tail as argument

nlines=`wc -l a.txt | awk '{print $1}'`

nlines=`expr $nlines - $1`
hlines=`expr $nlines - $1`

tail -$nlines a.txt | head -$hlines

# EOF

should work.

- ramd.

HPE Software Rocks!
John Poff
Honored Contributor

Re: head / tail function

Hi,

This is one way to do it using head and tail:

head -4 file | tail +2


The problem with head and tail is that they have a limited buffer space to work with, so they work fine with smaller files but not with large files. Probably Perl is a better choice to work with most any size file. You can do it like this with Perl:

perl -ne '2..4 and print' file

JP
Ramkumar Devanathan
Honored Contributor

Re: head / tail function

Sorry I misunderstood as a script to remove n lines from beginning and end of file.

Probably perl would be a better option as pointed out.

- ramd.
HPE Software Rocks!
Goran Koruga
Honored Contributor

Re: head / tail function

Or even sed :

sed -ne '2,5p' filename

HTH,
G.