繁体   English   中英

Perl文件正则表达式不会替换文本

[英]Perl file regex doesn't replace text

如果这不是重复的操作,我会感到惊讶,但似乎无法在任何地方找到解决此问题的方法。 我试图用另一个字符串替换文件中给定字符串的所有实例。 我遇到的问题是该脚本会打印替换的版本,但保留原始版本。 我是Perl的新手,所以我确定这是一个琐碎的问题,而且我遗漏了一些东西

码:

my $count;
my $fname = file_entered_by_user;
open (my $fhandle, '+<', $fname) or die "Could not open '$fname' for read: $!";

for (<$fhandle>) {
    $count += s/($item_old)/$item_new/g;
    print $fhandle $_;
}   
print "Replaced $count occurence(s) of '$item_old' with '$item_new'\n";
close $fhandle;

原始文件:

This is test my test file where
I test the string perl script with test
strings. The word test appears alot in this file
because it is a test file.

结果文件:

This is test my test file where
I test the string perl script with test
strings. The word test appears alot in this file
because it is a test file
This is sample my sample file where
I sample the string perl script with sample
strings. The word sample appears alot in this file
because it is a sample file.

预期结果文件:

This is sample my sample file where
I sample the string perl script with sample
strings. The word sample appears alot in this file
because it is a sample file.

附加信息:

  • $item_old$item_new由用户提供。 在给出的示例中,我将test替换为sample
  • 我对这种问题的一线解决方案不感兴趣。 它将与更大的程序集成在一起,因此可以从终端运行的单行解决方案不会有太大帮助。

问题是您正在使用+<模式,认为它会按您认为的那样工作。 您要做的是首先读取文件中的所有行,将文件句柄位置放在文件末尾,然后在其后打印行。

这条线

for (<$fhandle>) {

读取文件句柄的所有行并将它们放在列表中,然后循环遍历该列表。 它会一直读取到eof为止,然后才添加您的更改。

如果要使解决方案正常工作,则必须在打印之前倒回文件句柄。

seek($fhandle, 0, 0);

尽管我认为这些解决方案不是很好。 尤其是当有内置功能可以处理此类情况时:

perl -pi.bak -we 's/$item_old/$item_new/g' yourfile.txt

-p标志的-i标志可将您的代码应用于文本文件,并进行相应更改,并保存扩展名为.bak的副本。 当然,您必须提供要进行的替代,因为您没有提供。

编辑:我刚刚看到您不想要一线。 好吧,要执行此单行代码的操作,您只需要打开适当的文件句柄并在旧文件上复制更改的文件即可。 因此,基本上:

use strict;
use warnings;
use File::Copy;

open my $old, "<", $oldfile or die $!;
open my $new, ">", $newfile or die $!;

while (<$old>) {
    s/$item_old/$item_new/g
    print $new $_;
}
copy $newfile, $oldfile or die $!;

考虑到处理文件副本有多么容易,大多数时候,使用允许在同一文件句柄上进行读取和写入的模式要比使用它复杂得多。

暂无
暂无

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

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