如果這不是重複的,我會感到驚訝,但我似乎無法找到解決此問題的解決方案。我試圖用另一個字符串替換文件中給定字符串的所有實例。我遇到的問題是腳本打印替換的版本,但保留原文。我很新的perl的,所以我敢肯定,這是一個簡單的問題,我想的東西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
由用戶提供的。在給出的例子中,我用sample
代替test
。- 我對這個問題的單行解決方案不感興趣。它將與更大的程序集成,因此可以從終端運行的單線解決方案不會太有用。
謝謝,這解決了我的問題 – JamoBox
不客氣。 – TLP