Naveen Sangwan
Naveen Sangwan

Reputation: 861

How to add a new tag in xml file using shell scripting?

I have an xml file like

<changeSet id="1" author="naveen" dbms="oracle">
      <sqlFile path="/appl/Liquibase/sql/IntialVersion.sql" />
    </changeSet>
    <changeSet id="2" author="naveen"  dbms="oracle">
      <sqlFile path="/appl/Liquibase/sql/FirstRev.sql" />
    </changeSet>
    <changeSet id="3" author="naveen"  dbms="oracle">
      <sqlFile path="/appl/Liquibase/sql/23_12_2011.sql" />
    </changeSet>

I want to add a new changeSet tag like below using shell scripting

 <changeSet id="4" author="naveen"  dbms="oracle">
      <sqlFile path="/appl/Liquibase/sql/24_12_2011.sql" />
    </changeSet>

Is there any simple way to do this in shell scripting? I have to change id and sql file name also in the tag.

Upvotes: 0

Views: 1969

Answers (2)

kubanczyk
kubanczyk

Reputation: 5959

Quick, dirty, unreliable. Does not parse XML - this just assumes that your input file will always retain the current line formatting.

cat test.xml

<intro>
a\b&c;
d$e
</intro>
<changeSet id="1" author="naveen" dbms="oracle">
      <sqlFile path="/appl/Liquibase/sql/IntialVersion.sql" />
    </changeSet>
    <changeSet id="2" author="naveen"  dbms="oracle">
      <sqlFile path="/appl/Liquibase/sql/FirstRev.sql" />
    </changeSet>
    <changeSet id="3" author="naveen"  dbms="oracle">
      <sqlFile path="/appl/Liquibase/sql/23_12_2011.sql" />
    </changeSet>
<outro>
</outro>

Determine the line number of last changeSet tag

line_no="`grep -n '</changeSet>$' test.xml | cut -f1 -d: | tail -n 1`" ; echo "$line_no"

Add new changeSet

[[ -n "$line_no" ]] && sed "$line_no"'s#$#\n<changeSet id="4" author="naveen"  dbms="oracle">\n  <sqlFile path="/appl/Liquibase/sql/24_12_2011.sql" />\n</changeSet>#' test.xml > test.xml.new

cat test.xml.new

<intro>
a\b&c;
d$e
</intro>
<changeSet id="1" author="naveen" dbms="oracle">
      <sqlFile path="/appl/Liquibase/sql/IntialVersion.sql" />
    </changeSet>
    <changeSet id="2" author="naveen"  dbms="oracle">
      <sqlFile path="/appl/Liquibase/sql/FirstRev.sql" />
    </changeSet>
    <changeSet id="3" author="naveen"  dbms="oracle">
      <sqlFile path="/appl/Liquibase/sql/23_12_2011.sql" />
    </changeSet>
<changeSet id="4" author="naveen"  dbms="oracle">
  <sqlFile path="/appl/Liquibase/sql/24_12_2011.sql" />
</changeSet>
<outro>
</outro>

Upvotes: 1

Andrey Adamovich
Andrey Adamovich

Reputation: 20683

It's not really a well-formed XML file, but if you just want to append to the end of the file, then use echo or cat command and send its output to the end of the file with >> operator.

Upvotes: 0

Related Questions