How to add an attribute in a tag in XML file by command-line?

7,361

Solution 1

You should not parse xml with sed, use an xml parser like xmlstarlet instead. For your task it would be:

xmlstarlet ed -O --inplace --insert "/book" --type attr -n Book_Width -v A xml_file

The file content is then:

<book name="Sed tutorial" price="250" Book_Width="A"/>
  • The ed means edit mode to edit the xml tree
  • -O omits the xml tag
  • We want to insert something with --insert
  • "/book" is the path where to insert
  • --type attr: it's an attribute, we want to insert
  • The name -n of the attribute
  • The value -v

Solution 2

in sed "a" appends a pattern IN A NEW LINE.

what you want to do is replace (substitute). Let's use a colon as separator for clarity:

sed 's:\(<book.*\)\(/>\):\1 Book_Width="A"\2:'

anything in \( .. \) is a pattern memorized by the order of appearance and recalled by \indexnumber , e.g. \1 will reproduce the first pattern saved.

So we are memorizing <book name="Sed tutorial" price="250" as pattern 1 and /> as pattern 2 and just insert Book_Width="A" in the middle.

echo '<book name="Sed tutorial" price="250"/>' | sed 's:\(<book.*\)\(/>\):\1 Book_Width="A"\2:'
<book name="Sed tutorial" price="250" Book_Width="A"/>

Solution 3

With awk you can do something like this:

Supposing the line is in file file1.xml then:

awk -F '/' '{print $1,"Book_Width=\"A\"",FS,$2}' file1.xml
Share:
7,361

Related videos on Youtube

krishna
Author by

krishna

Updated on September 18, 2022

Comments

  • krishna
    krishna over 1 year

    I am trying to add field at the end of tag using sed script. Suppose I have a tag in XML file:

    <book name="Sed tutorial" price="250"/>
    

    Now I want to add field as Book_Width="A" after end of <book/> tag so that my tag becomes:

    <book name="Sed tutorial" price="250" Book_Width="A"/>
    

    I tried with sed:

    sed '/<book "[^>]*>/ a Book_Width="A"'
    

    but it gives:

    <book name="Sed tutorial" price="250"/>
    Book_Width="A"
    
  • krishna
    krishna over 8 years
    can I update xml_file rather printing its output
  • chaos
    chaos over 8 years
    @krishna Yes with --inplace I added it to my answer
  • Angel Todorov
    Angel Todorov over 8 years
    This is not checking that the tag is "book"
  • krishna
    krishna over 8 years
    If Book_Width="A" already present in XML file then how can we skip that tag
  • user32929
    user32929 almost 5 years
    In general a solution using sed or awk is only going to work on a subset of XML; if it works on the subset of XML that you apply it to, then that's fine. Just be aware that it will break as soon as it gets unexpected input; and if you put it into production, then we will see a slew of StackOverflow questions from people who want to know how to generate your chosen (proprietary and probably undocumented) subset of XML. Don't laugh - it happens all the time.