【问题标题】:In Perl replacement command empties the file under Windows在 Perl 替换命令清空 Windows 下的文件
【发布时间】:2016-04-26 02:26:13
【问题描述】:

我有以下命令:

perl -pi.bak -e "s/pattern//" $file_name

当我在 perl 脚本中执行它时,它会清空文件(我看到 .bak 文件,它不是空的)。当我在 shell 中执行它时,它可以工作。可能是什么问题?

问题是在Windows下,在Linux下可以正常工作。

编辑 1: 我也试过这个,它也空了:

sub replace_pattern_in_file
{
    my ($file, $pattern, $replacement) = @_;

    open my $in, "<", $file;
    unlink $file;

    open my $out, ">", $file;
    while(my $line = <$in>)
    {
        $line =~ s/$pattern/$replacement/g;
        print $out $line;
    }
}

【问题讨论】:

  • 你的模式是什么?
  • 重新编辑 1,这在 Windows 上不起作用,因为它没有匿名文件。

标签: windows perl shell


【解决方案1】:

你错了;这在 Windows 和 unix 系统上的工作方式相同。在任一类型的系统上,只有当模式完全匹配每一行(包括换行符)时,您才会得到您描述的行为。

>echo foo>file

>echo bar>>file

>echo moo>>file

>perl -pi.bak -e "s/o//" file

>type file
fo
bar
mo

【讨论】:

    猜你喜欢
    • 2017-12-27
    • 1970-01-01
    • 2012-03-29
    • 2016-10-08
    • 2019-02-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-16
    相关资源
    最近更新 更多