Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Printing entire file when regex matches

Status
Not open for further replies.
Jun 3, 2007
84
US
Hello all I have a script that I am working on. I am trying to print the entire contents of a file when a regex match is found once instead of what $_ is holding after a match.

So if a match is found I want to stop looking and just print the entire contents of the file. I am kinda stuck as to how to escape the while loop in order to print the entire contents instead of just the line that matches the regex.

Instead of adding/working with the entire script I just created another script with the part that I am having trouble with. Below is a sample script that I am trying to get this part working.

Thanks for the help in advanced.

Code:
#!/usr/bin/perl
use strict;
use warnings;

my $search_file = $ARGV[0];
open( DATA_FILE, "< $search_file" ) or die "Can't open $search_file : $!";

while ( <DATA_FILE> ) {
    if ( $_ =~ /Test/smgi ) {
        print "$_";
    }
}
 
Hi

Better change it to make two passes : one to seek and one to print, if needed.
Code:
#!/usr/bin/perl
use strict;
use warnings;

my $search_file = $ARGV[0];
open( DATA_FILE, "< $search_file" ) or die "Can't open $search_file : $!";

[red]my $found=0;[/red]

while ( <DATA_FILE> ) {
  [red]if ($found) { print } else {[/red]
    if ( $_ =~ /Test/smgi ) {
      [red]$found=1;[/red]
      [red]seek DATA_FILE,0,0;[/red]
    }
  }
}
[red]close DATA_FILE;[/red]

Feherke.
 
Same basic concept without the flag:

Code:
#!/usr/bin/perl
use strict;
use warnings;

my $search_file = $ARGV[0];
open( DATA_FILE, "< $search_file" ) or die "Can't open $search_file : $!";

while ( <DATA_FILE> ) {
   if (/Test/io ) {
      seek DATA_FILE,0,0;
      print <DATA_FILE>;
    }
  }
}
close DATA_FILE;

"print" is a list operator so it will print the entire file if you use it with a filehandle. You may want to use a "flag" though if you wish to determine that a match was or was not found later in the script.

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
You mean, it will do sequential processing instead of slurping in the entire file into the memory first ?

I don't know if it first reads the entire file into memory then prints or not. Good question.

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top