如何在特定行之前将文件的内容插入另一个文件 [英] How can I can insert the contents of a file into another file right before a specific line

查看:38
本文介绍了如何在特定行之前将文件的内容插入另一个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I can insert the contents of a file into another file right before a specific line using sed?

示例我有 file1.xml,其中包含以下内容:

example I have file1.xml that has the following:

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

和file2.xml有以下内容:

and file2.xml has the following:

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

如何将file2的内容插入到file1之前

how can I insert the contents of file2 into file1 just before

<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  

但我想之前插入它.

感谢您的帮助

推荐答案

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

如果你想要 sed,这是一种方法

if you want sed, here's one way

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

这篇关于如何在特定行之前将文件的内容插入另一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆