Showing posts with label find. Show all posts

Searching multiple strings in multiple files in a directory

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

Search a string in multiple files recursively

Almost every unix programmer will need this at least once in a day.
For searching a string abc in all the files in the current direcory we use:
grep 'abc' *

If you want to serach in files which are under any sub directories also including the files in the current directory then we have to combine both find and grep:

find . -type f|xargs grep 'abc'

Another possible way is using exec of find command:
find . -type f -exec grep 'abc' {} \;

Archiving files in a directory - tar command

Below is the command for archiving all the files from the current directory.

find . -type f | xargs -d "\n" tar -czvf backup.tar.gz

the above command  also works for files with name containing spaces.

Find and replace a string in all the files recursively

Below are some useful commands to  find and replace a string in all the files recursively in unix:

find . -type f|xargs perl -pi -e 's/source/target/g'

or
find . -type f -exec perl -pi -e 's/source/target/g' {} \;
or
find . -type f -exec sed -i 's/source/target/g' {} \;

All the three are logically similar