繁体   English   中英

如何在脚本中用Perl替换文件中的字符串(不在命令行中)

[英]How to replace string in a file with Perl in script (not in command line)

我想替换文件中的字符串。 我当然可以用

 perl -pi -e 's/pattern/replacement/g' file

但是我想用脚本来做。

还有其他方法可以代替system("perl -pi -es/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;
}

您可以使用-i开关轻松复制Perl的功能。

{
    local ($^I, @ARGV) = ("", 'file');
    while (<>) { s/foo/bar/; print; }
}

您可以尝试以下简单方法。 查看它是否最适合您的要求。

use strict;
use warnings;

# Get file to process
my ($file, $pattern, $replacement) = @ARGV;

# Read file
open my $FH, "<", $file or die "Unable to open $file for read exited $? $!";
chomp (my @lines = <$FH>);
close $FH;

# Parse and replace text in same file
open $FH, ">", $file or die "Unable to open $file for write exited $? $!";
for (@lines){
    print {$FH} $_ if (s/$pattern/$replacement/g);
}
close $FH;

1;

file.txt:

Hi Java, This is Java Programming.

执行:

D:\swadhi\perl>perl module.pl file.txt Java Source

file.txt

Hi Source, This is Source Programming.

您可以使用

sed 's/pattern/replacement/g' file > /tmp/file$$ && mv /tmp/file$$ file

某些sed版本支持-i命令,因此您不需要tmpfile。 -i选项将创建临时文件并为您移动,基本上,这是相同的解决方案。

另一个解决方案(Solaris / AIX)可以将here结构与vi结合使用:

vi file 2>&1 >/dev/null <@
1,$ s/pattern/replacement/g
:wq
@

我不喜欢vi解决方案。 当您的模式具有/或另一个特殊字符时,将很难调试出了什么问题。 当用shell变量replacement ,您可能需要首先检查内容。

您可以处理问题中的用例,而无需重新创建-i标志的功能或创建一次性变量。 将标志添加到Perl脚本的shebang中,并阅读STDIN:

#!/usr/bin/env perl -i

while (<>) {
    s/pattern/replacement/g;
    print;
}

用法:保存脚本,使其可执行(使用chmod +x ),然后运行

path/to/the/regex-script test.txt

(或regex-script test.txt如果脚本已保存到$ PATH中的目录中。)


超越问题:

如果您需要运行多个顺序替换,那就是

#!/usr/bin/env perl -i

while (<>) {
    s/pattern/replacement/g;
    s/pattern2/replacement2/g;
    print;
}

如问题示例中所示,将不备份源文件。 就像在-e oneliner中一样,您可以通过将backupExtension添加到-i标志来备份到file.<backupExtension> 例如,

#!/usr/bin/env perl -i.bak

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM