简体   繁体   中英

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.

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>

它不是一个格式正确的XML文件,但是如果您只想追加到文件的末尾,则可以使用echocat命令,并使用>>运算符将其输出发送到文件的末尾。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM