#!/usr/bin/perl use Getopt::Long; sub usage { my $msg= "Usage: $0 \n" . "This modifies all the files on the list line-by-line\n" . "using the included perl code. The code is run line by line,\n" . "as if it were in a 'while (<>)' loop or -w mode. For example,\n" . "the code 's/oldstring/newstring/' would replace oldstring\n" . "with newstring throughout all the files. \n" . "Options: \n" . " -h Print this message. \n" . " -saveold Saves the old version of the file as '.old'\n" . " -s Treat the entire file as a single line which the\n" . " the code then acts on.\n" . "Options: \n"; return $msg; } my ($help, $saveold, $single); GetOptions("h" => \$help, "help" => \$help, "saveold" => \$saveold, "s" => \$single); if ($help) { print usage(); exit; } my $code = shift; my @filelist= (); foreach (@ARGV) { push @filelist, glob($_); } foreach (@filelist) { my $thisfile= $_; my $mode = (stat($thisfile))[2]; my $tempfile= $_ . '.temp'; open(THISFILE, "$thisfile"); open(TEMPFILE, ">$tempfile"); if ($single) { my $string; while () { $string.=$_; } $_= $string; eval($code); print TEMPFILE $_; } else { while () { eval($code); print TEMPFILE $_; } } close(THISFILE); close(TEMPFILE); if ($saveold) { rename($thisfile,"$thisfile.old"); } else { unlink($thisfile); } rename($tempfile, $thisfile); chmod($mode,$thisfile); } # end of foreach @filelist