Disclaimer: You are looking at a post I wrote some time ago. The information and opinions contained within may be outdated and may differ from my current views. Please proceed accordingly.

Recursive Linux Grep with Color

Oct 31, 2003 5:08 PM
Tags:
update this version does not allow the string to have spaces. Damn. I need to make it smarter about parsing its arguments. In the meantime I've fixed that bug.

This is actually version 2.0 of my previous script. It's all in a single perl executable now, instead of being split into a separate shell script and perl script.

Please use at your own risk. Special characters may give you headaches — if you want to search for some, you'll need a backslash to escape them, and if your directory name has special characters, like |, this script is the least of your worries. Also, I'm no Perl guru, and there's probably some way for a person to pass nasty stuff into the backticks, if they can execute this script with arbitrary arguments.

#!/usr/bin/perl
$string = join " ", @ARGV; # ugly hack; there must be a better way
unless ($string) {
    $error = "Usage: regrep [string]\nRecursively searches all files ";
    $error .= "in current directory for [string]\n";
    print $error;
    exit 1;
}

# Ideally, we'd parse the arguments better.
#$directory = shift @ARGV;
unless ($directory) { $directory = '.'; }

@grepOutput = `egrep -rn --color=always "$string" $directory`;

for $line (@grepOutput) {
    if ($line =~ /^BINARY.*/) {
	; # do nothing
    } elsif ($line =~ /^([^:]*)(:)([^:]*)(:)(.*)/) {
	print "\033[1;34m";
	print $1;
	print "\033[0m";
	print $2;
	print "\033[1;36m";
	print $3;
	print "\033[0m";
	print $4;
	print $5;
	print $6;
	print "\n";
    }
}

Comments: Recursive Linux Grep with Color

Nice script. It came in very handy for me.

Posted by: George on July 30, 2007 10:23 AM | permalink

No more comments! Either someone has violated Godwin's Law, I'm tired of the discussion or, most likely, the ten-week window has closed. You can, however, contact me through email.