Skip to content

Instantly share code, notes, and snippets.

@RubeRad
Created February 25, 2011 17:48
Show Gist options
  • Save RubeRad/844184 to your computer and use it in GitHub Desktop.
Save RubeRad/844184 to your computer and use it in GitHub Desktop.
Open ascii files, make substitutions, and write them back out
#! /bin/perl
# subinplace.pl
use Getopt::Std;
%opt = ();
getopts('tvsSh', \%opt);
$usage = "Usage:\n";
$usage .= "subinplace.pl [-htv] 'before_pat' 'after_pat' files...\n";
$usage .= " -h _h_elp\n";
$usage .= " -t _t_est (print changed lines, but don't modify any files)\n";
$usage .= " -v _v_erbose (print lines as they are being modified)\n";
$usage .= "NOTE: in before_pat, you can use . for one wildcard or .* for multiple\n";
$usage .= "\n";
if ($opt{h}) {
print $usage;
exit;
}
$bef = shift @ARGV;
$aft = shift @ARGV;
# special undocumented switches to override either the entire before or after pattern with
if ($opt{S}) { $bef = "\\" }
if ($opt{s}) { $aft = "\\" }
for $f (@ARGV) {
open IN, $f;
@lines = (<IN>);
close IN;
open OUT, ">$f" unless $opt{t};
for (@lines) {
if (s!$bef!$aft!g) {
print STDOUT if ($opt{t} or $opt{v});
}
print OUT unless $opt{t};
}
close OUT unless $opt{t};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment