Monday, April 29, 2024
5
rated 0 times [  5] [ 0]  / answers: 1 / hits: 1144  / 3 Years ago, wed, november 10, 2021, 12:19:53

I have around 4000 XML files and I need to replace the value of both <filename> and <path> fields.
I need to replace those fields dynamically. e.g. images0001.xml should have images0001 inside the two fields, images0002.xml should have images0002 inside the two fields, etc.


I've already used this command to rename the files sequentially:


rename 's/.+/our $i; sprintf("images%04d.jpg", 1+$i++)/e' *

And I also used this command to delete the .jpg extension that was in the two fields I'm trying to change:


sed -i 's/.jpg//g' Annotations/*

Here is the current state of the contents of the XML files:


<annotation>
<folder></folder>
<filename>1608644703_2.rf.fa179c1e6c47d72d668ac3d83c7f79d1</filename>
<path>1608644703_2.rf.fa179c1e6c47d72d668ac3d83c7f79d1</path>
<source>
<database>roboflow.ai</database>
</source>
<size>
<width>416</width>
<height>416</height>
<depth>3</depth>
</size>
<segmented>0</segmented>
<object>
<name>megot</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<occluded>0</occluded>
<bndbox>
<xmin>129</xmin>
<xmax>292</xmax>
<ymin>145</ymin>
<ymax>351</ymax>
</bndbox>
</object>
</annotation>

And here is how I need the files to be changed:


<annotation>
<folder></folder>
<filename>images0001</filename>
<path>images0001</path>
<source>
<database>roboflow.ai</database>
</source>
<size>
<width>416</width>
<height>416</height>
<depth>3</depth>
</size>
<segmented>0</segmented>
<object>
<name>megot</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<occluded>0</occluded>
<bndbox>
<xmin>129</xmin>
<xmax>292</xmax>
<ymin>145</ymin>
<ymax>351</ymax>
</bndbox>
</object>
</annotation>

I'm looking for a way to do this in command line, but I can't figure out a solution after searching for a while!


Any help will be appreciate. Thanks in advance!


More From » command-line

 Answers
4

You would need an XML tool(like xmlstarlet) ... so:


sudo snap install xmlstarlet

In a loop ... so:


for f in *.xml
do
xml ed -L -u "(//annotation/filename)" -v "${f/.xml/}" -u "(//annotation/path)" -v "${f/.xml/}" "$f"
done

[#140] Thursday, November 11, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
horicgly

Total Points: 36
Total Questions: 126
Total Answers: 104

Location: Iceland
Member since Thu, Dec 1, 2022
1 Year ago
horicgly questions
Thu, Jun 23, 22, 15:02, 2 Years ago
Thu, May 5, 22, 14:58, 2 Years ago
Mon, Oct 4, 21, 16:07, 3 Years ago
;