Search String in multiple files
Posted on 2011-06-05 15:30:34
by Geert Vandeweyer
The following program is a standard tool for me when searching existing code for specific snippets I need and know I have, just not where i have them...
Place the program in your /home/$user/bin directory and make it executable.
geert@ubuntu: chmod u+x searchterm.pl
You can now search in case sensitive or insensitive manner for specific strings in multiple files. It will output the file it was found in, and the relevant lines, including their line number.
geert@ubuntu: searchterm.pl location
=> Searching for 'location', in a case sensitive way
########################
# setclass.js
########################
3 newwindow=window.open(url,'name','scrollbars=1,height=400,width=500,location=no,menubar=no,status=no,screenX=100,screenY=100');
########################
# viewportmonitor.js
########################
12 window.location.reload();
=> Found 2 hit(s) on location in this directory
geert@ubuntu: searchterm.pl location
=> Searching for 'location', in a case insensitive way
########################
# setclass.js
########################
3 newwindow=window.open(url,'name','scrollbars=1,height=400,width=500,location=no,menubar=no,status=no,screenX=100,screenY=100');
########################
# viewportmonitor.js
########################
12 window.location.reload();
########################
# parser.js
########################
14 Location = '/var/www/site/parsers/';
=> Found 3 hit(s) on location in this directory
Copy this code to /home/$user/bin/searchterm.pl:
#!/usr/bin/perl
$|++;
use Getopt::Std;
getopts('i',\%opts); # -i for case insensitive search
# get all files (skip directories)
@list = `ls -l | grep ^- 2>/dev/null`;
$term = $ARGV[0];
if ($opts{'i'}) {
print "\n => Searching for '$term', in a case insensitive way\n\n";
}
else {
print "\n => Searching for '$term', in a case sensitive way\n\n";
}
my $found = 0;
foreach (@list) {
chomp($_);
$file = $_;
$file =~ m/\d\d:\d\d (.*)$/;
$file = $1;
my $output = '';
if ($opts{'i'}) {
$output = `cat -n '$file' | grep -i '$term' 2>/dev/null`;
}
else {
$output = `cat -n '$file' | grep '$term' 2>/dev/null`;
}
if ($output ne "" ) {
$found++;
print "########################\n";
print "# $file\n";
print "########################\n";
print $output;
}
}
print "\n => Found $found hit(s) on $term in this directory\n";
Batch, Searching
Comments
Loading Comments