Operating System - HP-UX
1830935 Members
2278 Online
110017 Solutions
New Discussion

Re: Perl - read between lines in a file

 
SOLVED
Go to solution
ES UNIX Team
Advisor

Perl - read between lines in a file

All,
I was wondering if anyone had a better way to read between lines in a file. I can do it with a few loops, but it is messy and time consuming. I'd like a better way.

The file would be:
A
bunch of lines
B
bunch of lines
C
bunch of lines
D

and I want the "bunch of lines" between line B and line C. I will know what line B and line C are, but nothing else in the file.

Anybody know a really clean way to do this in Perl?
4 REPLIES 4
Scott Palmer_1
Trusted Contributor
Solution

Re: Perl - read between lines in a file

open(INFILE,"<$INFILE")|| die;
while) {
if (/$PAT1/ ... /$PAT2/ ) {
print "$_";
}
}

this prints everyting between patern1 and patern2

Regards
Scott
Patrick Wallek
Honored Contributor

Re: Perl - read between lines in a file

This isn't a complete script but maybe something like this:

#!/usr/bin/sh

FLAG=N
LINE1="Text of line you want to start printing from"
LINE2="Text of line you want to stop printing"
while read LINE
do
if [ "${LINE}" = "${LINE2}" ] ; then
FLAG=N
fi

if [ "${FLAG}" = "Y" ] ; then
echo ${LINE}
fi

if [ "${LINE}" = "${LINE1}" ] ; then
FLAG=Y
fi

done < inputfile

I think something like that should work. If that doesn't work it should be pretty close.
Marvin Strong
Honored Contributor

Re: Perl - read between lines in a file

#perl -ne 'if(/line B/.../line C/){print}' inputfile

Rodney Hills
Honored Contributor

Re: Perl - read between lines in a file

To reword Marvins,

perl -ne '$seq=/^B/../^C/; print if ($seq > 1 and substr($seq,-2) ne "E0")' inputfile

This will exclude the "B" and "C" lines

HTH

-- Rod Hills
There be dragons...