从 file1 读取行并替换 file2 中的行标记的最快方法

Quickest method to read lines from file1 and replace line tag in file2

有两个文件file1和file2。它们的内容是:

文件 1 - 输入

Line1
Line2
Line3
Line4

文件 2 - 输入

<head>
<intro> This is an introduction </intro>
 <line> this is a line1 </line>
 </head>
<head>
 <intro> This is another intro </intro>
 <line> this is a line2 </intro>
 </head>
<head>
<intro> This is an introduction </intro>
 <line> this is a line3 </line>
 </head>
<head>
 <intro> This is another intro </intro>
 <line> this is a line4 </intro>
 </head>

想要读取文件 1 并将文件 2 中的行标记值替换为 Line1、Line2、Line3、Line4(参见输出)。哪种方法最简单(sed、awk、grep、perl、python ...)?

输出

    <head>
    <intro> This is an introduction </intro>
     <line> Line1 </line>
     </head>
    <head>
     <intro> This is another intro </intro>
     <line> Line2 </intro>
     </head>
    <head>
    <intro> This is an introduction </intro>
     <line> Line3 </line>
     </head>
    <head>
     <intro> This is another intro </intro>
     <line> Line4 </intro>
     </head>

如果您认为这是重复的,请 link 复制。我试图通过看起来相似但 none 我找到的解决方案。

编辑: 以防万一有人想要 append/concatenate 而不是替换,可以很容易地修改 @cdarke python2 代码中的 markline 表达式,如下所示并使用。


markline = re.sub(r'</line>$',''+subt+'</line>',markline)

使用 GNU sed 和 bash 的进程替换:

sed -e '/<line>[^<]*<\/[^>]*>/{R '<(sed 's|.*| <line> & </line>|' file1) -e 'd;}' file2

输出:

<head>
<intro> This is an introduction </intro>
 <line> Line1 </line>
 </head>
<head>
 <intro> This is another intro </intro>
 <line> Line2 </line>
 </head>
<head>
<intro> This is an introduction </intro>
 <line> Line3 </line>
 </head>
<head>
 <intro> This is another intro </intro>
 <line> Line4 </line>
 </head>

最简单的方法可能是您熟悉的方法。如果您了解 Perl 和 Python(以及 Ruby 和 Lua),这很容易。 'Easy' 是主观的。

(编辑示例以添加空格)

这里是Python2版本:

import re

lines = open('file1').readlines()

with open('file2') as fh:
    for markline in fh:
        if '<line>' in markline:
            subt = lines.pop(0).rstrip()
            markline = re.sub(r'<line>.*</line>', '<line> ' + subt + ' </line>',
                          markline)

        print markline,

这是一个 Perl 版本:

use strict;
use warnings;

open(my $fh1, 'file1') or die "Unable to open file1 for read: $!";

my @lines = <$fh1>;
chomp(@lines);
close($fh1);

open(my $fh2, 'file2') or die "Unable to open file2 for read: $!";

while (<$fh2>) {
    s/<line>.*<\/line>/'<line> ' . shift(@lines) . ' <\/line>'/e;
    print 
}

close($fh2);

我假设输入数据中有拼写错误。

我展示的代码有效,但不够灵活。所有这些语言都有几个 XML 解析器,你真的应该学习其中一种语言和一个 XML 解析器。