perl -p -i.bak -e 's/search_str/replace_str/g' filename
here what is -p -i.bak /s
and /g
perl -p -i.bak -e 's/search_str/replace_str/g' filename
here what is -p -i.bak /s
and /g
1.causes perl to assume the following loop around your script, which makes it iterate over filename arguments somewhat like sed:
See perldoc perlrun.
This one-liner changes every occurrence of search_str
to replace_str
in every line of the file, automatically printing the resulting line.
The -i.bak
switch causes it to change the file in-place and store a backup to another file with the .bak
extension.
From perlrun:
-p
causes Perl to assume the following loop around your program, which makes it iterate over filename arguments somewhat like sed:
LINE: while (<>) { ... # your program goes here } continue { print or die "-p destination: $!\n"; }
-p
: assume 'while (<>) { ... }
'
loop around program and print each
processed line too.-i.bak
: change the input file
(filename
) inplace and create the
file filename.bak
as backup.s in s/
: to mark substitutiong
- make the substitution
globally..that is don't stop after
first replacement.This piece of code:
perl
-p
-i.bak
-e
's/search_str/replace_str/g'
filename
Is essentially the same as:
#! /usr/bin/env perl
$extension = '.orig';
LINE:
while (<>) {
# -i.bak
if ($ARGV ne $oldargv) {
if ($extension !~ /\*/) {
$backup = $ARGV . $extension;
} else {
($backup = $extension) =~ s/\*/$ARGV/g;
}
rename($ARGV, $backup);
open(ARGVOUT, ">$ARGV");
select(ARGVOUT);
$oldargv = $ARGV;
}
s/search_str/replace_str/g;
} continue {
print; # this prints to original filename
}
select(STDOUT);