Search code examples
xmlshellawksedxmllint

Extract XML Tag and append to a specific location in another xml using Shell Script


I have two license xml files: a-license.xml and b-license.xml. The format of both the license files is same. I want to merge them into a single file.

Sample Input:

File a-license.xml contains

   <company-license>
   <generator></generator>
   <customer></customer>
   <orderid></orderid>
   <expiration></expiration>
   <license>
      <module>A</module>
      <license_key>xxxx-xxxx-xxxxx</license_key>
   </license>
   </company-license>

File b-license.xml contains

  <company-license>  
   <generator></generator>
   <customer></customer>
   <orderid></orderid>
   <expiration></expiration>
   <license>
      <module>B</module>
      <license_key>yyyy-yyyy-yyyy</license_key>
   </license>
   </company-license>

Desired output should be something like

  <company-license> 
   <generator></generator>
   <customer></customer>
   <orderid></orderid>
   <expiration></expiration>
   <license>
      <module>A</module>
      <license_key>xxxx-xxxx-xxxxx</license_key>
   </license>
   <license>
      <module>B</module>
      <license_key>yyyy-yyyy-yyyy</license_key>
   </license>
   </company-license>

I want to extract <license> tag from a-license.xml and append it below the <license> tag of b-license.xml.

How can I do this?


Solution

  • sed -n '1,/<license>/{/<license>/d;p;}' a-license.xml > new-license.xml
    sed -n '/<license>/,/<\/license>/p' a-license.xml >> new-license.xml
    sed -n '/<license>/,/<\/company-license>/p' b-license.xml >> new-license.xml
    

    or shorter:

    sed -n '1,/<\/license>/p' a-license.xml > new-license.xml
    sed -n '/<license>/,$p' b-license.xml >> new-license.xml
    

    Output to file new-license.xml:

    <company-license>
       <generator></generator>
       <customer></customer>
       <orderid></orderid>
       <expiration></expiration>
       <license>
          <module>A</module>
          <license_key>xxxx-xxxx-xxxxx</license_key>
       </license>
       <license>
          <module>B</module>
          <license_key>yyyy-yyyy-yyyy</license_key>
       </license>
       </company-license>