use*_*289 0 regex shell scripting perl
我想替换文件中的字符串.我当然可以用
perl -pi -e 's/pattern/replacement/g' file
Run Code Online (Sandbox Code Playgroud)
但是我想用脚本来做.
还有其他方法可以做到system("perl -pi -e s/pattern/replacement/g' file")
吗?
-i
利用您仍然可以读取未链接的文件句柄,您可以看到它在perlrun中使用的代码.自己做同样的事情.
use strict;
use warnings;
use autodie;
sub rewrite_file {
my $file = shift;
# You can still read from $in after the unlink, the underlying
# data in $file will remain until the filehandle is closed.
# The unlink ensures $in and $out will point at different data.
open my $in, "<", $file;
unlink $file;
# This creates a new file with the same name but points at
# different data.
open my $out, ">", $file;
return ($in, $out);
}
my($in, $out) = rewrite_file($in, $out);
# Read from $in, write to $out as normal.
while(my $line = <$in>) {
$line =~ s/foo/bar/g;
print $out $line;
}
Run Code Online (Sandbox Code Playgroud)