Search code examples
awksedxmlstarlet

Merge xml tag value by command-line


I am trying to merge publisher and isbn value into title tag using sed. But I can't find any example here that match my requirement. example as below

from this

<book>
  <title>The Big Book of Silly Jokes for Kids</title>
  <publisher>Rockridge Press</publisher>
  <isbn>ISBN-10</isbn>
</book>

to this

<book>
  <title>[Rockridge Press ISBN-10] The Big Book of Silly Jokes for Kids</title>
  <publisher>Rockridge Press</publisher>
  <isbn>ISBN-10</isbn>
</book>

Solution

  • With xmlstarlet:

    xml ed -u /book/title -x "concat('[',/book/publisher/text(),' ',/book/isbn,'] ',/book/title)" book.xml
    

    output:

    <?xml version="1.0"?>
    <book>
      <title>[Rockridge Press ISBN-10] The Big Book of Silly Jokes for Kids</title>
      <publisher>Rockridge Press</publisher>
      <isbn>ISBN-10</isbn>
    </book>
    

    EDIT: space added after ']' The '--inplace' is optional to 'edit file inplace'.