Searching multiple strings in multiple files in a directory

Tuesday, March 11, 2014 , , , , 2 Comments

I have a list of strings in a file separated by a new line.
for example:
input.txt
temp1
temp2
temp3
Now I have a directory with multiple dat files like:
>ls -1 *.dat
one.dat
two.dat
three.dat
And many more dat like like above with random names. Now I want to search for all the strings in input.txt in all the dat files present in  directory(let's say current working directory).This is what I came up with:
create a perl script given below and name it as anything you wish(I named here as temp.pl).place the file input.txt in the current working directory.
#!/usr/bin/perl -w

open (INP,"input.txt") or die $!;
while(<INP>)
{
my $cmd="find . -name \"*.dat\"|xargs grep -w -i $_";
my $output=`$cmd`;
 if($output!~/^\s*$/)
 {
 print $_."\n";
 print "------------------\n";
 print $output."\n";
 print "-------------------\n";
 }
}
exit;
Run this script as :
>./temp.pl
This solved my need.I hope it solves yours too :)

2 comments:

  1. nice script,

    what about something like that :

    the example with gnu paraller(1), but xargs -Px would work too:

    cat input.txt | parallel grep -iR {} *.dat

    i dont have a proper shell right now, but in theory it should work.

    1. http://www.gnu.org/software/parallel/

    Regards,
    Alex

    ReplyDelete
  2. just tested, that works:

    cat input.txt | xargs -P3 -I {} grep -iR "{}" *.dat

    ReplyDelete