替换perl中的文本
我试图在文件中找到一个特定的字符串,并希望用另一个字符串替换该字符串。然后我还想替换文件中的这个字符串。我正在使用以下代码:替换perl中的文本,perl,file-io,Perl,File Io,我试图在文件中找到一个特定的字符串,并希望用另一个字符串替换该字符串。然后我还想替换文件中的这个字符串。我正在使用以下代码: open(FILEB,"+<File B (2).txt"); $hostNameA="Any string\n"; foreach $lineB(FILEB) { seek(FILEB,-length($lineB),1); $lineB=~s/$hostNameB/$hostNameA/;
open(FILEB,"+<File B (2).txt");
$hostNameA="Any string\n";
foreach $lineB(FILEB)
{
seek(FILEB,-length($lineB),1);
$lineB=~s/$hostNameB/$hostNameA/;
print FILEB $lineB;
}
open(FILEB),+使用相同句柄写入文件将销毁原始文件
open IN, '<', 'path_to_file' or die $!
open OUT, '>', 'path_to_replaced_file' or die $!;
while (my $line = <IN>) {
$line =~ s/something/tosomething/g;
print OUT $line;
}
close OUT;
close IN;
# if you wish, backup old file, and rename new file
在“,”中打开“,”到“替换文件”的路径“或骰子$!;
while(我的$line=){
$line=~s/something/tosomething/g;
打印$line;
}
收尾;
接近;
#如果愿意,请备份旧文件并重命名新文件
这个怎么样
$perl-pi.bak-e's/hostNameB/hostNameA/g'“文件B(2.txt)”
从“文件B(2.txt)”中读取该文件,然后使用regex的/hostNameB/hostNamea/g对其进行编辑
并备份原始文件。如果您在linux上工作,甚至不需要打开文件,也不需要创建备份文件-
open IN, '<', 'path_to_file' or die $!
open OUT, '>', 'path_to_replaced_file' or die $!;
while (my $line = <IN>) {
$line =~ s/something/tosomething/g;
print OUT $line;
}
close OUT;
close IN;
# if you wish, backup old file, and rename new file
#!/usr/bin/perl
#Commandline
my $command = "sed -i 's/FOO/BAR/g' /mydir/myfile.txt";
#Execute Command
`$command`;
上面的脚本将在myfile.txt中将所有出现的字符串“FOO”替换为“BAR”什么是“path\u to\u file”和“path\u to\u replaced\u file”?“path\u to\u file”是您的原始文件,另一个是被替换的文件。