[英]how can i modify a text file by perl
I want to make 'find/change' function. 我想进行“查找/更改”功能。
change some words through using s/ / / or tr/ / / but it's not working, i think. 我想通过使用s / / /或tr / / /更改一些单词,但是它不起作用。
open(TXT, ">>text.txt"); my $str = <TXT>; $str =~ s/'a'/'b'/; print TXT $str;
Your program opens a file for append , so you won't be able to read from it and the line my $str = <TXT>
will set $str
to undef
. 您的程序将打开一个文件进行添加 ,因此您将无法读取该文件,并且my $str = <TXT>
会将$str
设置为undef
。
You can write this as a one-line console command, using 您可以使用以下命令将其编写为单行控制台命令
perl -i.backup -pe"s/'a'/'b'/g" myfile
which substitutes the string 'a'
(including the quotes) with the string 'b'
throughout the file, and saves a backup to myfile.backup
它将整个文件中的字符串'a'
(包括引号)替换为字符串'b'
,并将备份保存到myfile.backup
Or you can write a program like this 或者您可以编写这样的程序
use strict;
use warnings;
open my $fh, '<', 'myfile' or die qq{Unable to open input file: $!};
while (<$fh>) {
s/'a'/'b'/g;
print $_;
}
which leaves the input file intact and sends the modified data to STDOUT, so it can be redirected to a new file with the command 这样可以保持输入文件完整无缺并将修改后的数据发送到STDOUT,因此可以使用以下命令将其重定向到新文件
perl modify.pl myfile > myfile.new
Look at this example: 看这个例子:
...
open RH, "text.txt" or die $!;
chomp(my @lines = <RH>);
close RH;
open WH, ">text.txt" or die $!;
foreach my $line (@lines) {
$line =~ s/'a'/'b'/;
print WH "$line\n";
}
close WH;
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.