user1440061
user1440061

Reputation: 445

Searching through file on Perl

Okay so I need to read in a file, go through each line and find where there is the string ERROR. This is what I have so far:

open(LOGFILE, "input.txt") or die "Can't find file";

$title = <LOGFILE>;

$\=' ' ;
while (<>){
    foreach $title(split){
        while (/^ERROR/gm){
            print "ERROR in line $.\n";
        }
    }
}
close LOGFILE;

So the problem that I have is that it only looks at the first word of each line. So if the input is

boo far ERROR

It won't register an error. any help would be greatly appreciated! I'm new to perl so please try and keeps things basic. Thanks!

Upvotes: 2

Views: 9836

Answers (2)

kvnhn
kvnhn

Reputation: 3125

This is a more elegant approach, and I fixed the regex issue. ^ matched the start of a line.

open(LOGFILE, "input.txt") or die "Can't find file";

while(<LOGFILE>) {
   print "ERROR in line $.\n" if(/ERROR/);
}
close LOGFILE;

Or how about from the command line:

perl -n -e 'print "ERROR in line $.\n" if(/ERROR/);' input.txt

-n implicitly loops for all lines of input -e executes a line of code

To output to a file:

perl -n -e 'print "ERROR in line $.\n" if(/ERROR/);' input.txt > output.txt

While this is a good/simple example of using Perl, if you're using a Unix shell, grep does what you want with no need for scripting (thanks to TLP in the OP comments):

grep -n ERROR input.txt > output.txt

This is actually prints the matching line itself, with its line number.

Upvotes: 6

Oleg V. Volkov
Oleg V. Volkov

Reputation: 22481

Of course it won't, because ^ in front of your regexp means "start of line". Remove it and it will catch ERROR anywhere. You shouldn't do any splitting tricks either. You need to find ERROR anywhere? Then just write so:

while (<>){
   if (/ERROR/){
      print "ERROR in line $.\n";
   }
}

Upvotes: 1

Related Questions