tags:

views:

162

answers:

2

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

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>

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>

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

<group ref="StandardMessageTrailer" required="true"/>

so it will look like this:

       <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>

I know how to insert after that line using

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

but I want to insert it before.

appreciate the help

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

if you want sed, here's one way

sed  -e '/StandardMessageTrailer/r file2' -e 'x;$G' file1
ghostdog74
Your `sed` version doesn't print the last line of file1. If you add `-e '$G'` after the `'x'` then it will, but it will fail if the line with the regex is the last line in file1 by printing that line *then* the contents of file2.
Dennis Williamson
@dennis thanks. with regard to the last line regex issue. i will bet on it not happening, for now. :) as you can see, my preferred solution is not sed.
ghostdog74
A: 

If you can bear to make two passes, you can use a marker:

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

The trouble with trying to do it in one pass is that there's no way (that I know of) other than 'r' to insert the contents of a file, and 'r' does so in the output stream, out of reach of manipulation, after sed is finished with the line. So if the 'Standard' is in the last line, whatever you do with it will be over by the time file2 appears.

Beta