-1

I have more than 1k xml files and in a loop I want to do few changes to xml file

original

<annotation>
  <folder>VOC2014_instance/person</folder>
  <filename>set00_V000_69.jpg</filename>
  <source> ... </source>
  ....
  ....
</annotation>

modified should look like

<annotation>
  <folder>VOC2014_instance/person</folder>
  <filename>set00_V000_69.jpg</filename>
  <path>/home/red/MyDataset/set00_V000_69.jpg</path>
  <source> ... </source>
  ....
  ....
</annotation>

So, I tried writing this code

for file in $PWD/*.xml
do
    sed -i 's/filename>/[\n]    <path></path>/g' $file
done

What I'm doing is finding filename> and then append new line with \n + 4 spaces + <path>/home/red/$filename</path> + newline

I know I'm not doing it right but first I don't how to pick name of file b/w and then append a new line at end with space

abhimanyuaryan
  • 3,882
  • 5
  • 41
  • 83
  • 5
    Because xml files are not line-based files, the general advice is to use xml libraries to do this sort of edit, not line-based tools. – Gem Taylor Aug 19 '19 at 11:36
  • 1
    Choose the right tool first. I suggest to use an XML/HTML parser (xmlstarlet, e.g.). [You can't parse \[X\]HTML with regex](http://stackoverflow.com/a/1732454/3776858) – Cyrus Aug 19 '19 at 11:41
  • how about this? https://stackoverflow.com/questions/3095434/inserting-newlines-in-xml-file-generated-via-xml-etree-elementtree-in-python xml etree in python? – abhimanyuaryan Aug 19 '19 at 11:41
  • @Cyrus how about xml etree in python? – abhimanyuaryan Aug 19 '19 at 11:41
  • This might help: [How do I insert an element directly after another element with XMLStarlet?](https://stackoverflow.com/q/7473720/3776858) – Cyrus Aug 19 '19 at 11:45
  • @Cyrus so this can used with bash command? like `xml ed -i /rootnode/element-d -t elem -n element-c -v "" file.xml` add this after do statement or something? – abhimanyuaryan Aug 19 '19 at 11:51

2 Answers2

0

So this what the complete command looks like:

for file in $PWD/*.xml
do
do sed -i 's/>Images</>VOC2012</g' $file
filename=$(basename "$file")
xmlstarlet edit --inplace \
           --append "//annotation/filename" \
           --type elem --name "path" --value "/home/red/MyDataset/music/Images/$filename" $file
done
abhimanyuaryan
  • 3,882
  • 5
  • 41
  • 83
-2

You can get the filename with filename=$(basename "$file")

user239512
  • 62
  • 3