App-GrepUtils
view release on metacpan or search on metacpan
script/grep-terms view on Meta::CPAN
#!perl
use 5.010001;
use strict;
use warnings;
use Log::ger;
use Getopt::Long;
our $AUTHORITY = 'cpan:PERLANCAR'; # AUTHORITY
our $DATE = '2022-05-03'; # DATE
our $DIST = 'App-GrepUtils'; # DIST
our $VERSION = '0.006'; # VERSION
my $opt_highlight_terms;
my @grep_argv;
my @pos_terms;
sub parse_cmdline {
Getopt::Long::Configure('auto_abbrev', 'pass_through');
my $res = GetOptions(
'version|V' => sub {
no warnings 'once';
say "grep-terms version ", ($main::VERSION // 'dev');
exit 0;
},
'help' => sub {
print <<USAGE;
Usage:
grep-terms [GREP-TERM-OPTIONS]... <TERMS> [GREP-OPTIONS | FILES]...
grep-terms --help
grep-terms --version|-V
Grep-term Options:
Examples:
% grep-terms "foo bar baz -qux -quux" -i file.txt
For more details, see the manpage/documentation.
USAGE
exit 0;
},
'highlight-terms' => \$opt_highlight_terms,
);
exit 99 if !$res;
log_trace "ARGV: %s", \@ARGV;
die "grep-terms: Please supply terms" unless @ARGV;
my $terms = shift @ARGV;
#log_trace "terms: %s", $terms;
my $re = '^';
for my $term (split /\s+/, $terms) {
if ($term =~ s/^-//) {
$re .= "(?!.*$term)";
} else {
$re .= "(?=.*$term)";
push @pos_terms, $term;
}
}
push @grep_argv, '-P', '-e', $re, @ARGV;
}
sub run {
if ($opt_highlight_terms && @pos_terms) {
require IPC::System::Options;
IPC::System::Options::system(
{shell=>1, log=>1, die=>1},
"grep", @grep_argv, \"|", "grep", "--color=always", "-P", join("|", @pos_terms),
);
} else {
log_trace "Exec: %s", ["grep", @grep_argv];
exec "grep", @grep_argv;
}
}
# MAIN
parse_cmdline();
run();
1;
# ABSTRACT: Print lines that match terms
# PODNAME: grep-terms
__END__
( run in 1.204 second using v1.01-cache-2.11-cpan-d7a12ab2c7f )