2010-03-25 57 views
16

如何在使用sed的特定行之前将文件内容插入另一个文件?如何在特定行之前将文件内容插入另一个文件

的例子,我有一个具有以下file1.xml:

 <field tagRef="376"> 
     </field> 
     <field tagRef="377"> 
     </field> 
     <field tagRef="58"> 
     </field> 
     <group ref="StandardMessageTrailer" required="true"/> 
    </fieldList> 
</message> 

和file2.xml具有如下:

 <field tagRef="9647"> 
      <description>Offset</description> 
     </field> 
     <field tagRef="9648"> 
      <description>Offset Units/Direction</description> 
     </field> 
     <field tagRef="9646"> 
      <description>Anchor Price</description> 
     </field> 

我怎么能只

之前插入的文件2内容到文件1
<group ref="StandardMessageTrailer" required="true"/> 

所以它看起来就像这样:

 <field tagRef="376"> 
     </field> 
     <field tagRef="377"> 
     </field> 
     <field tagRef="58"> 
     </field> 
     <field tagRef="9647"> 
      <description>Offset</description> 
     </field> 
     <field tagRef="9648"> 
      <description>Offset Units/Direction</description> 
     </field> 
     <field tagRef="9646"> 
      <description>Anchor Price</description> 
     </field> 
     <group ref="StandardMessageTrailer" required="true"/> 
    </fieldList> 
</message> 

我知道如何使用

sed 'group ref="StandardMessageTrailer"/r file2.xml' file1.xml > newfile.xml 

该行后面插入,但我想之前将其插入。

欣赏的帮助

+0

我很想看到一个实际的sed解决方案 - 我知道这应该是可能的东西像'/ StandardMessageTrailer/{x; r插入; G}'但这不是很... – Cascabel 2010-03-25 00:54:42

回答

19
f2="$(<file2)" 
awk -vf2="$f2" '/StandardMessageTrailer/{print f2;print;next}1' file1 

如果你想SED,这里有一个方法

sed -e '/StandardMessageTrailer/r file2' -e 'x;$G' file1 
+3

您的'sed'版本不打印file1的最后一行。如果在''x''之后添加'-e'$ G'',那么它会,但是如果具有正则表达式的行是file1的最后一行,则通过打印该行然后* file2的内容将失败。 – 2010-03-25 07:29:47

+0

@dennis谢谢。关于最后一行正则表达式问题。现在,我敢打赌它不会发生。 :)你可以看到,我的首选解决方案不是sed。 – ghostdog74 2010-03-25 08:07:34

+1

在MacOS上,您可以通过在命令中添加-i.bak直接写入文件:'sed -i.bak -e'/ StandardMessageTrailer/r file2'-e'x; $ G'file1' – 2016-01-22 11:14:35

3

如果你能忍受做两遍,你可以使用一个标记:

sed '/Standard/i MARKER' file1.xml | sed -e '/MARKER/r file2.xml' -e '/MARKER/d' 

试图一次性完成的麻烦是除了'r'之外没有办法(我知道)插入文件的内容,并且'r'在输出流中是这样做的,无法操作,之后sed完成了该行。所以如果'标准'在最后一行,那么无论你用它做什么都会在file2出现的时候结束。

1

通常我这样做:

  1. 文件1,文件读取插入内容
  2. 文件2,在头从文件1插入阅读内容文件2
  3. script script snippet:

    sed "\$r ${file2}" ${file1} > tmpfile
    mv tmpfile ${file2}

0

我尝试了不同的解决方案,并从测试版的一个所做的工作对我来说。

摘要:

  • 我想不同的文件插入到主文件
  • 我想用标记说,我想将这些文件插入

例:
创建2个文件:

cloud_config.yml:

coreos: 
__ETCD2__ 

etcd2.yml:

etcd2: 
    name:       __HOSTNAME__ 
    listen-peer-urls:    http://__IP_PUBLIC__:2380 
    listen-client-urls:   http://__IP_PUBLIC__:2379,http://127.0.0.1:2379 

然后我们就可以运行该脚本:

sed '/Standard/i __ETCD2__' cloud_config.yml \ 
| sed -e "/__ETCD2__/r etcd2.yml" > tmpfile 
sed "s|__ETCD2__||g" tmpfile > cloud_config.yml 

最后,我们得到了:

coreos: 
    etcd2: 
    name:       __HOSTNAME__ 
    listen-peer-urls:    http://__IP_PUBLIC__:2380 
    listen-client-urls:   http://__IP_PUBLIC__:2379,http://127.0.0.1:2379 
相关问题