Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: search for a string and return previous relating string if found

by poj (Abbot)
on Dec 06, 2017 at 20:10 UTC ( [id://1205046]=note: print w/replies, xml ) Need Help??


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

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).

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1205046]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (6)
As of 2024-03-28 22:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found