The UNIX and Linux Forums  

Go Back   The UNIX and Linux Forums > Top Forums > Shell Programming and Scripting
.
google unix.com




View Single Post in the UNIX and Linux Forums - Click on the Thread or Permalink to View Entire Thread -->
  #1 (permalink)  
Old 01-24-2008
tqlam tqlam is offline
Registered User
  
 

Join Date: Jul 2004
Posts: 12
Perl how to move pointer to previous line in a txt file?

I have a text file that has blocks of text. Each block starts with ### and ends with End_###.
I wrote a perl script to search a string from line 2 (ignore any line starts with ###) of each block
if matched, need to print that whole block. According to the input file in below, it will print blocks #02, #04, #05.
Here is my question, I have no problems matching the SEARCH_STR, but once matched, how do I move back previous lines?
e.g. in block #02, matched in line 3, but I need to print lines 1 & 2.

Thanks in advance for any help!

MY SCRIPT:
=========
#!/46020/local/bin/perl -w
#
if ($#ARGV != 0) {
print "You must provide a search criteria.\n";
exit;
}
my $query = $ARGV[0];
my $INPUT = "/mypath/inputFILE.txt";
my $line;
my $tag = 0;
my @results = ();

open (FILE, "<$INPUT") or die "Cannot open '$INPUT' file: $!";
while ($line = <FILE>) {
next if ($line =~ /^#[0-9][0-9].* - / || $line =~ /^\s*$/);
if ($line =~ /$query/i) {
$tag = 1;
}
if ($line =~ /^End_#/ && $tag == 1) {
push (@results,$line) if ($tag == 1);
$tag = 0;
}
push (@results,$line) if ($tag == 1);
}
close (FILE);
print "@results\n";
exit;


INPUTFILE:
========
#01 - block start line here
some text here
more text here
more lines
more lines
more lines
End_#01

#02 - block start line here
some text here
this line contains the SEARCH_STR and something
more lines
more lines
End_#02

#03 - block start line here
some text here
more text here
more lines
more lines
more lines
End_#03

#04 - block start line here
some text here
more lines
more lines
the SEARCH_STR is here and something
some text here
more lines
more lines
more lines
End_#04

#05 - block start line here
some text here
more lines
the SEARCH_STR is here and something
more lines
End_#05


#06 - block start line here
some text here
more text here
more lines
more lines
more lines
End_#06