Home > Net >  search multi line string from multiple files in a directory
search multi line string from multiple files in a directory

Time:08-09

the string to to be searched is:

   the file_is being created_automaically {
  period=20ns     }    

the perl script i am using is following ( this script is working fine for single line string but not working for multi line )

#!/usr/bin/perl
my $dir = "/home/vikas";
my @files = glob( $dir . '/*' );
#print "@files";
system ("rm -rf $dir/log.txt");

my $list;
foreach $list(@files){
if( !open(LOGFILE, "$list")){
open (File, ">>", "$dir/log.txt");
select (File);
print " $list \: unable to open file"; 
close (File);

else {   
while (<LOGFILE>){
if($_ =~ /".*the.*automaically.*\{\n.*period\=20ns.*\}"/){ 
open (File, ">>", "$dir/log.txt");
select (File);

print " $list \: File contain the required string\n";  
close (File);

     break;
}
}   
close (LOGFILE);
}
}

CodePudding user response:

This code does not compile, it contains errors that causes it to fail to execute. You should never post code that you have not first tried to run.

The root of your problem is that for a multiline match, you cannot read the file in line-by-line mode, you have to slurp the whole file into a variable. However, your program contains many flaws. I will demonstrate. Here follows excerpts of your code (with fixed indentation and missing curly braces).

First off, always use:

use strict;
use warnings;

This will save you many headaches and long searches for hidden problems.

system ("rm -rf $dir/log.txt");

This is better done in Perl, where you can control for errors:

unlink "$dir/log.txt" or die "Cannot delete '$dir/log.txt': $!";

foreach my $list (@files) {
#       ^^ 

Declare the loop variable in the loop itself, not before it.

if( !open(LOGFILE, "$list")){
    open (File, ">>", "$dir/log.txt");
    select (File);
    print " $list \: unable to open file"; 
    close (File);

You never have to explicitly select a file handle before you print to it. You just print to the file handle: print File "....". What you are doing is just changing the STDOUT file handle, which is not a good thing to do.

Also, this is error logging, which should go to STDERR instead. This can be done simply by opening STDERR to a file at the beginning of your program. Why do this? If you are not debugging a program at a terminal, for example via the web or some other process where STDERR does not show up on your screen. Otherwise it is just extra work while debugging.

open STDERR, ">", "$dir/log.txt" or die "Cannot open 'log.txt' for overwrite: $!";

This has the added benefit of you not having to delete the log first. And now you do this instead:

if (! open LOGFILE, $list ) {
    warn "Unable to open file '$list': $!";
} else ....

warn goes to STDERR, so it is basically the same as print STDERR.

Speaking of open, you should use three argument open with explicit file handle. So it becomes:

if (! open my $fh, "<", $list ) 

} else {
    while (<LOGFILE>) {

Since you are looking for a multiline match, you need to slurp the file(s) instead. This is done by setting the input record separator to undef. Typically like this:

my $file = do { local $/; <$fh> };    # $fh is our file handle, formerly LOGFILE

Next how to apply the regex:

if($_ =~ /".*the.*automaically.*\{\n.*period\=20ns.*\}"/) { 

$_ =~ is optional. A regex automatically matches against $_ if no other variable is used.

You should probably not use " in the regex. Unless you have " in the target string. I don't know why you put it there, maybe you think strings need to be quoted inside a regex. If you do, that is wrong. To match the string you have above, you do:

if( /the.*automaically.*{.*period=20ns.*}/s ) { 

You don't have to escape \ curly braces {} or equal sign =. You don't have to use quotes. The /s modifier makes . (wildcard character period) also match newline, so we can remove \n. We can remove .* from start or end of string, because that is implied, regex matches are always partial unless anchors are used.

break;

The break keyword is only used with the switch feature, which is experimental, plus you don't use it, or have it enabled. So it is just a bareword, which is wrong. If you want to exit a loop prematurely, you use last. Note that we don't have to use last because we slurp the file, so we have no loop.

Also, you generally should pick suitable variable names. If you have a list of files, the variable that contains the file name should not be called $list, I think. It is logical that it is called $file. And the input file handle should not be called LOGFILE, it should be called $input, or $infh (input file handle).

This is what I get if I apply the above to your program:

use strict;
use warnings;

my $dir     = "/home/vikas";
my @files   = glob( $dir . '/*' );
my $logfile     = "$dir/log.txt";

open STDERR, ">", $logfile or die "Cannot open '$logfile' for overwrite: $!";

foreach my $file (@files) {
    if(! open my $input, "<", $file) {
        warn "Unable to open '$file': $!"; 
    } else {
        my $txt = do { local $/; <$fh> };
        if($txt =~ /the.*automaically.*{.*period=20ns.*}/) {
            print " $file  : File contain the required string\n";
        }
    }
}

Note that the print goes to STDOUT, not to the error log. It is not common practice to have STDOUT and STDERR to the same file. If you want, you can simply redirect output in the shell, like this:

$ perl foo.pl > output.txt

CodePudding user response:

The following sample code demonstrates usage of regex for multiline case with logger($fname,$msg) subroutine.

Code snippet assumes that input files are relatively small and can be read into a variable $data (an assumption is that computer has enough memory to read into).

NOTE: input data files should be distinguishable from rest files in home directory $ENV{HOME}, in this code sample these files assumed to match pattern test_*.dat, perhaps you do not intend to scan absolutely all files in your home directory (there could be many thousands of files but you interested in a few only)

#!/usr/bin/env perl

use strict;
use warnings;
use feature 'say';

my($dir,$re,$logfile);

$dir = '/home/vikas/';
$re  = qr/the file_is being created_automaically \{\s period=20ns\s \}/;

$logfile = $dir . 'logfile.txt';

unlink $logfile if -e $logfile;

for ( glob($dir . "test_*.dat") ) {
    if( open my $fh, '<', $_ ) {
        my $data = do { local $/; <$fh> };
        close $fh;
        logger($logfile, "INFO: $_ contains the required string")
            if $data =~ /$re/gsm;
    } else {
        logger($logfile, "WARN: unable to open $_");
    }
}

exit 0;

sub logger {
    my $fname = shift;
    my $text  = shift;

    open my $fh, '>>', $fname
        or die "Couldn't to open $fname";
        
    say $fh $text;
    
    close $fh;
}

Reference: regex modifies, unlink, perlvar

  • Related