从另一个文件中的列表替换文件中的文本? [英] Replacing text in a file from a list in another file?
问题描述
我以前问过这个问题,但根据给出的答案,我认为我没有正确解释。 p>
我有一个名为 backup.xml
的文件,长度为28,000行,包含短语 ** *
在其中766次。我也有一个名为 list.txt
的文件,它有766行,每个都有不同的关键字。
我基本上需要做的是将 list.txt
中的每一行插入 backup.xml
中以替换766个地方 ***
。
下面是 list.txt中包含的内容的示例
:
Anaheim
Anchorage
Ann Arbor
Antioch
Apple Valley
Appleton
下面是一个例子, c $ c> *** 在 backup.xml
中:
< title> *** Hosting Services - Company Review< / title>
因此,例如,第一行有 ***
提到的应该根据上面的示例改为:
< title> Anaheim Hosting Services - Company评论< / title>
任何帮助将非常感谢。提前感谢!
在这种情况下,您可能会将XML视为纯文本。
所以读取XML文件,并用从关键字文件中读取的行替换每个标记的出现:
#!/ usr / bin / perl
使用strict;
使用警告;
使用autodie qw(open);
my $ xml_file ='backup.xml';
my $ list_file ='list.txt';
my $ out_file ='out.xml';
my $ pattern ='***';
#我假设所有文件都是utf8编码的
open(my $ xml,'<:utf8',$ xml_file);
open(my $ list,'<:utf8',$ list_file);
open(my $ out,'>:utf8',$ out_file);
while(< $ xml>)
{s {\Q $ pattern\E} {my $ kw =< $ list> ;; chomp $ kw; $ kw} eg;
print {$ out} $ _;
}
rename $ out_file,$ xml_file;
I asked this question before but don't think I really explained it properly based on the answers given.
I have a file named backup.xml
that is 28,000 lines and contains the phrase ***
in it 766 times. I also have a file named list.txt
that has 766 lines in it, each with different keywords.
What I basically need to do is insert each of the lines from list.txt
into backup.xml
to replace the 766 places ***
is mentioned.
Here's an example of what's contained in list.txt
:
Anaheim
Anchorage
Ann Arbor
Antioch
Apple Valley
Appleton
Here's an example of one of the lines with ***
in it from backup.xml
:
<title>*** Hosting Services - Company Review</title>
So, for example, the first line that has ***
mentioned should be changed to this according to the sample above:
<title>Anaheim Hosting Services - Company Review</title>
Any help would be greatly appreciated. Thanks in advance!
In this case you can probably get away with treating the XML as pure text. So read the XML file, and replace each occurrence of the marker with a line read from the keyword file:
#!/usr/bin/perl
use strict;
use warnings;
use autodie qw( open);
my $xml_file = 'backup.xml';
my $list_file = 'list.txt';
my $out_file = 'out.xml';
my $pattern='***';
# I assumed all files are utf8 encoded
open( my $xml, '<:utf8', $xml_file );
open( my $list, '<:utf8', $list_file );
open( my $out, '>:utf8', $out_file );
while( <$xml>)
{ s{\Q$pattern\E}{my $kw= <$list>; chomp $kw; $kw}eg;
print {$out} $_;
}
rename $out_file, $xml_file;
这篇关于从另一个文件中的列表替换文件中的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!