Created
November 22, 2019 16:37
-
-
Save isaaclw/c0b77af5d75ae86d228125d9cb8aed75 to your computer and use it in GitHub Desktop.
Replaces a string within multiple files specified on the command line #perl
This file contains hidden or 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
#!/usr/bin/perl | |
# | |
# Replaces a string within multiple files | |
# specified on the command line | |
$mv = '/bin/mv'; | |
$tmp = '/tmp'; | |
$op = shift || die("Usage: $0 perlexpr [filenames]\n"); | |
if (!@ARGV) { | |
@ARGV = <STDIN>; | |
chop(@ARGV); | |
} | |
foreach $file (@ARGV) { | |
if (!-f $file) { | |
print "Skipping non-regular file: $file\n"; | |
next; | |
} | |
if (-B $file) { | |
print "Skipping binary file: $file\n"; | |
next; | |
} | |
$outfile = "$tmp/$file.$$"; | |
open(FILE, $file) || | |
die("Couldn't open $file: $!\n"); | |
undef $/; | |
$_ = <FILE>; | |
close(FILE); | |
if (eval $op) { | |
system("mkdir -p $outfile"); | |
system("rm -r $outfile"); | |
open(OFILE, "> $outfile") || | |
die("Couldn't open $outfile: $!\n"); | |
print OFILE; | |
close(OFILE); | |
system($mv, '-f', $file, "$file.bak"); | |
system($mv, '-f', $outfile, $file); | |
print "File changed: $file\n"; | |
} | |
else { | |
print "No change to file: $file\n"; | |
} | |
} | |
exit(0); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment