Created
February 25, 2011 17:50
-
-
Save RubeRad/844187 to your computer and use it in GitHub Desktop.
Construct and execute multiple 2-argument commands using patterns to specify input/output pairs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /bin/perl | |
# multi.pl | |
# Parse command-line switches | |
use Getopt::Std; | |
%opt = (); | |
getopts('htqorlgO:', \%opt); | |
$usage = "Usage: multi.pl [-hqorlt] cmd before_pat after_pat [files]\n"; | |
$usage .= " -h _h_elp\n"; | |
$usage .= " -t _t_est (print, but don't execute cmds)\n"; | |
$usage .= " -q _q_uiet operation (no STDERR)\n"; | |
$usage .= " -o cmd -o after_file before_file\n"; | |
$usage .= " -O x cmd -x after_file before_file\n"; | |
$usage .= " -r cmd before_file > after_file\n"; | |
$usage .= " -l _l_ist commands which yield STDOUT\n"; | |
$usage .= " -g _g_lobal subsitution of before_pat->after_pat\n"; | |
if ($opt{h}) { | |
print $usage; | |
exit; | |
} | |
$cmd = shift @ARGV; | |
$befor = shift @ARGV; | |
$after = shift @ARGV; | |
unless (defined($cmd) and defined($befor) and defined($after)) { | |
print "Usage: multi cmd before_pat after_pat\n"; | |
exit(1); | |
} | |
@oldfiles = (@ARGV > 0 ? | |
@ARGV : | |
glob("*$befor*")); | |
foreach $old (@oldfiles) { | |
chomp $old; | |
$new = $old; | |
if ($opt{g}) { # global substitution | |
$new =~ s/$befor/$after/g; | |
} else { | |
$new =~ s/$befor/$after/; | |
} | |
if ($opt{o}) { # -o switch | |
$command = "$cmd -o $new $old"; | |
} elsif ($opt{O}) { | |
($lcmd = $cmd) =~ s/^(\S+)/$1 -$opt{O} $new/; | |
$command = "$lcmd $old"; | |
} elsif ($opt{r}) { # output redirection | |
$command = "$cmd $old > $new"; | |
} else { | |
$command = "$cmd $old $new"; | |
} | |
if ($opt{l}) { # list commands that yield STDOUT | |
$stdout = `$command`; | |
print "$command\n" if $stdout; | |
} else { | |
print "$command\n" unless $opt{q}; | |
system($command) unless $opt{t}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment