![](/img/trans.png)
[英]I want to do a search replace in perl. My file has strings like "time1", "+time1", "+time11", "time11".How do I differentiate between these 4 strings
[英]Rusty in perl. How do I read in a datafile, and then replace an entire line within that file if a specific string is found
我需要一些快速的 perl 幫助。 這就是我想要的:
1) 從命令行運行我的 perl 腳本,並將數據文件作為參數傳入 2) 搜索傳入的數據文件,並查找字符串中第一次出現的單詞。 將字符串所在的整行替換為另一行文本。 3)將更新的文件保存到自身(在文件內替換)。
例如,這樣的事情:
./myPerlScript.pl data.txt
數據文件是這樣的:
_DATA__
path/to/some/file
path/to/some/other/file
path/to/SUBTSTRING/file #replace entire line if SUBSTRING is found
path/to/file
但實際的data.txt
已更新(不寫入新文件)
與任何其他語言相同。
use Fcntl qw( SEEK_SET );
my $qfn = $ARGV[0];
open(my $fh, '+<', $qfn)
or die("Can't open \"$qfn\": $!\n");
# Read contents of file into $file.
my $file; { local $/; $file = <$fh>; }
if ($file =~ s/^.*SUBSTR.*/foo/mg) {
seek($fh, 0, SEEK_SET)
or die("seek: $!\n");
truncate($fh, 0)
or die("truncate: $!\n");
print($fh $file)
or die("print: $!\n");
close($fh)
or die("close: $!\n");
}
另一種方式:
在使用足夠新的 Perl 版本時執行以下操作會發生這種情況:
perl -nle'print /SUBSTR/ ? "foo" : $_' -i file
我們可以通過$^I
訪問這個功能
$^I = '';
while (<>) {
chomp;
say /SUBSTR/ ? "foo" : $_;
}
這種方法有兩個優點:
還有三個缺點:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.