in reply to search for a string and return previous relating string if found

I have the following text in many files

Are all the files in one directory and do the filenames have a pattern ?

poj
  • Comment on Re: search for a string and return previous relating string if found

Replies are listed 'Best First'.
Re^2: search for a string and return previous relating string if found
by Anonymous Monk on Dec 07, 2017 at 11:27 UTC

    the files are all in one folder, the only unique identifier of the files is they are all .txt

      In that case then glob would find the files

      #!/usr/bin/perl use strict; my $dir = 'c:/temp/tmp'; # directory to search my @files = glob("$dir/*.txt"); for my $filename (@files){ my $lineno = 0; print "Scanning $filename ..\n"; open IN,'<',$filename or die "Could not open $filename : $!"; my $iface; while (<IN>){ ++$lineno; if (/^interface\s+(.*)/){ $iface = $1; } if (/spanning-tree guard/){ print "$filename,$lineno,$iface,$_"; $iface = ''; } } }
      poj

        Just two nitpicks: glob splits its argument on whitespace, so $dir can't contain any whitespace - except if you do use File::Glob ':bsd_glob';, which I'd strongly recommend in this case. Also, filenames beginning with a dot will be ignored (which is probably fine but should be mentioned).