I am trying to write a Perl script which will do the following:
1. Open a file which, in each line, contains the location of multiple files (Say File A, file B)
2. Do an egrep on each of these files something like egrep "module|input|output"
3. Store the output of the egrep with the same file name A, B etc but in a different directory)
There are more constraints on the egrep, but I can add them later.
My question is how do I do steps 2 and 3? Where in, I execute a shell command on each line of my file which is opened by my Perl script. And the file location would be, for example, design/rtl/name.v
and I want the result of egrep to be stored in design/fake/name.v
In shell (bash) make a directory results and list your files one to a line in the file "list" and then just type this straight in at the bash prompt
for i in `cat list`;do egrep "string" $i > result/grep${i}; done
Here is similar in perl. The error behaviour is nicer, it might be a tiny bit faster: the real advantage would be that extra behaviours could be added easier. Save it as a file and run as "perl script list foo" where script is the filename of the script, list is the filename of the list of files and foo is the pattern being searched for
#!/usr/bin/perl
#
my ( $file, $pattern ) = @ARGV;
open( my $fh, $file ) || "die $! $file\n";
while (<$fh>) {
chomp; #trim newline from filename
my $togrep = $_;
open( my $grepfh, $togrep ) || warn "$togrep $!";
if ($grepfh) {
open( my $output, ">result/$togrep" ) || die "$togrep $!";
while ( grep( $pattern, <$grepfh> ) ) {
print $output $_;
}
}
}
Loop over the filenames like this:
while read file
do
egrep "module|imput|ouput" "$file" > "/another/directory/${file##*/}"
done < fileList.txt