tangetools/G/G
2018-03-04 17:55:50 +01:00

108 lines
2.2 KiB
Perl
Executable file

#!/usr/bin/perl
=pod
=head1 NAME
G - shorthand for multi level greps
=head1 SYNOPSIS
B<G> [[grep options] string] [[grep options] string] ...
=head1 DESCRIPTION
B<G> is a short hand of writing:
grep --option string | grep --option2 string2
=head1 EXAMPLE
Grep for lines with Foo but not Bar:
G Foo -v Bar
=head1 AUTHOR
Copyright (C) 2017 Ole Tange,
http://ole.tange.dk and Free Software Foundation, Inc.
=head1 LICENSE
Copyright (C) 2012 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
at your option any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
=head1 DEPENDENCIES
B<G> uses B<grep>.
=head1 SEE ALSO
B<openssl>
=cut
my $i = 0;
while(@ARGV) {
$_ = shift;
push @{$cmd[$i]}, $_;
if(/^[^-]/) {
$i++
}
}
exec join"|", map { "grep ".join(" ", shell_quote(@$_)) } @cmd;
sub shell_quote {
# Input:
# @strings = strings to be quoted
# Output:
# @shell_quoted_strings = string quoted with \ as needed by the shell
return wantarray ?
(map { shell_quote_scalar($_) } @_)
: (join" ",map { shell_quote_scalar($_) } @_);
}
sub shell_quote_scalar {
# Quote for other shells
my $a = $_[0];
if(defined $a) {
# zsh wants '=' quoted
# Solaris sh wants ^ quoted.
# $a =~ s/([\002-\011\013-\032\\\#\?\`\(\)\{\}\[\]\^\*\>\<\~\|\; \"\!\$\&\'\202-\377])/\\$1/g;
# This is 1% faster than the above
if(($a =~ s/[\002-\011\013-\032\\\#\?\`\(\)\{\}\[\]\^\*\<\=\>\~\|\; \"\!\$\&\'\202-\377]/\\$&/go)
+
# quote newline as '\n'
($a =~ s/[\n]/'\n'/go)) {
# A string was replaced
# No need to test for "" or \0
} elsif($a eq "") {
$a = "''";
} elsif($a eq "\0") {
$a = "";
}
}
return $a;
}