Adding an XML element to an XML file using sed command in a shell script

I use the sed command to insert an xml element into an existing xml file.

I have an xml file as

<Students>
    <student>
        <name>john</>
        <id>123</id>
    </student>
    <student>
        <name>mike</name>
        <id>234</id>
    </student>
</Students>

I want to add a new item as

    <student>
        <name>NewName</name>
        <id>NewID</id>
    </student>

So my new xml file will be

<Students>
    <student>
        <name>john</>
        <id>123</id>
    </student>
    <student>
        <name>mike</name>
        <id>234</id>
    </student>
    <student>
        <name>NewName</name>
        <id>NewID</id>
    </student>
</Students>

For this, I wrote a shell script as

#! /bin/bash

CONTENT="<student>
            <name>NewName</name>
            <id>NewID</id>
        </student>"

#sed -i.bak '/<\/Students>/ i \ "$CONTENT" /root/1.xml
sed -i.bak '/<\/Students>/ i \'$CONTENT'/' /root/1.xml

I get an error like

sed: can't read <name>NewName</name>: No such file or directory
sed: can't read <id>NewID</id>: No such file or directory
sed: can't read </student>: No such file or directory

And in the xml file is added only <student>. The remaining elements are not added. Does anyone know why this error?

+4
source share
3 answers

change this:

CONTENT="<student>
            <name>NewName</name>
            <id>NewID</id>
        </student>"

:

CONTENT="<student>\n<name>NewName</name>\n<id>NewID</id>\n</student>"

and then:

C=$(echo $CONTENT | sed 's/\//\\\//g')
sed "/<\/Students>/ s/.*/${C}\n&/" file
+5
source

unescaped newline sed, .. $CONTENT . sed , shell, .

, .

, r. :

, ;

$ cat file
<Students>
    <student>
        <name>john</>
        <id>123</id>
    </student>
    <student>
        <name>mike</name>
        <id>234</id>
    </student>
</Students>

, , ( ):

$ cat add.txt
    <student>
        <name>NewName</name>
        <id>NewID</id>
    </student>

( gnu sed):

$ sed '/<\/Students>/{ 
    r add.txt
    a \</Students>
    d 
}' file
<Students>
    <student>
        <name>john</>
        <id>123</id>
    </student>
    <student>
        <name>mike</name>
        <id>234</id>
    </student>
    <student>
        <name>NewName</name>
        <id>NewID</id>
    </student>
</Students>

, , - xml . . .

+3

(GNU sed Bash):

CONTENT='    <student>\
    <name>NewName</name>\
    <id>NewID</id>\
</student>'

sed '/<\/Students>/i\'"$CONTENT" file

Alternatively, add new students to the file and:

sed '/<\/Students>/e cat new_student_file' file
0
source

Source: https://habr.com/ru/post/1537614/


All Articles