- Published on
My adapted GREP for work
- Authors
- Name
- Filipe "Hegaja" Oliveira
- @hegaja
When looking for a more efficient way to search for text, I started to search for a script that would meet some basic requirements.
They are:
Different colors for each word selected in the search;
A simple and easy way to add new words to the search filter;
They should filter lines that only have that specific keyword.
When searching the internet for a script that could do this, I came across this script in Perl. To be honest, I had never used Perl before, but I was extremely pleased with the result.
#!/usr/bin/perl
use Getopt::Std;
use strict;
use Term::ANSIColor;
my %opts;
getopts('hic:l:',\%opts);
if ($opts{h}){
print<<EoF;
Use -l to specify the pattern(s) to highlight. To specify more than one
pattern use commas.
-l : A Perl regular expression to be colored. Multiple expressions can be
passed as comma separated values: -l foo,bar,baz
-i : makes the search case sensitive
-c : comma separated list of colors;
EoF
exit(0);
}
my $case_sensitive=$opts{i}||undef;
my @color=('bold red','bold blue', 'bold green', 'bold yellow',
'bold magenta', 'bold cyan', 'yellow on_blue',
'bright_white on_yellow', 'bright_yellow on_red', 'white on_black');
if ($opts{c}) {
@color=split(/,/,$opts{c});
}
my @patterns;
if($opts{l}){
@patterns=split(/,/,$opts{l});
}
else{
$patterns[0]='\*';
}
# Setting $| to non-zero forces a flush right away and after
# every write or print on the currently selected output channel.
$|=1;
while (my $line=<>)
{
my $want=0;
for (my $c=0; $c<=$#patterns; $c++){
if($case_sensitive){
if($line=~/$patterns[$c]/){
$line=~s/($patterns[$c])/color("$color[$c]").$1.color("reset")/ge;
$want++;
}
}
else{
if($line=~/$patterns[$c]/i){
$line=~s/($patterns[$c])/color("$color[$c]").$1.color("reset")/ige;
$want++;
}
}
}
print STDOUT $line if $want>0;
}
Using a cool alias, the command to use becomes trivial. In my case, I chose 'h'.
alias h="destination\of\script\h.sh -l "
To use it, just separate the keywords with a comma. If I want an expression, just add the expression in quotation marks.
h ERROR,FAIL,WARNING h SIGABRT,"end of file",epilif
I've been using this script for a few years. Unfortunately, I couldn't find the link (or remember the place) where I got this code. Credits go to this unknown dev.