我有2个文本文件。我正在编写一个perl脚本,其中我需要在文本文件中找到“无法解析”字符串,然后提取具有此字符串的整行。在“/”之后提取此字符串的一部分并将字符串存储在变量中。< / p>
然后我需要打开另一个文本文件,在此文本文件中找到存储的字符串并替换该字符串。
my $ldir = "/Android";
$RESULTS_FILE = $ldir.'/'.'results.html';
open OUT, ">>", $RESULTS_FILE;
open(IN,"<logcat.txt");
while(<IN>)
{
chomp;
if( $_ =~ m/Unable to parse/ )
{
my @string = split('/',$_);
print @string;
my $stream_name = $string[4];
while $srch(<OUT>)
{
chomp;
if( $srch =~ m/$stream_name/ )
{
// How to replace the line here?
}
}
}
}
请帮忙。
此致 拉姆金
答案 0 :(得分:0)
您需要读取文件,用某些内容替换所有出现的目标字符串,然后再将该文件保存回来:
#!/usr/bin/perl
use strict;
sub replace_string_in_file {
my ( $source, $target, $filename ) = @_;
my $filecontents = do {
open my $fd, "<" $filename;
local $/;
<$fd>;
};
$filecontents =~ s/$source/$target/mg;
open my $fd, ">", $filename;
print $fd $filecontents;
close($fd);
}
my $ldir = "/Android";
$RESULTS_FILE = $ldir.'/'.'results.html';
open(IN,"<logcat.txt");
while(<IN>)
{
chomp;
if( $_ =~ m/Unable to parse/ )
{
my @string = split('/',$_);
print @string;
my $stream_name = $string[4];
replace_string_in_file( $stream_name, "THIS IS THE REPLACEMENT", $RESULTS_FILE );
}
}