Use xmlstarlet to remove an entire element that matches an attribute value?
4
votes
2
answers
3878
views
My question is similar to [sed - Delete XML node containing certain element - Unix & Linux Stack Exchange](https://unix.stackexchange.com/questions/72157/delete-xml-node-containing-certain-element) . Trying to implement the suggestions there has kept me busy all day, but I haven't managed to get anything to work, so I am posting a question.
Within a bash script, I need to remove an entire `
element when the
id attribute matches a given value. I'm actually using user-groups to do part of this. Say a user is **not** in the group
folder_a; then the entire
element with attribute
id=".Folder_A"` should be deleted from config.xml. (I also delete the folder from disk.)
My bash script looks like this:
#!/bin/bash
grouplist=$(groups $theuser);
for foldername in '.Folder_A' '.Folder_B'; do
grpnm="${foldername,,}"|sed -e 's/^.//'
if ! [[ $grouplist =~ ${grpnm} ]]; then
perl -0777 -pe "s|()|$1=~ /id=\"$foldername\"/?"":$1|gse" config.xml > config.xml
rm -fr "$foldername"
else
echo "permitting access to ${foldername}"
fi
done
The perl command is **not** working. It is just one of many variants I have tried. I also tried sed. I would prefer to use xmlstarlet, but I had even more trouble with it.
**Edit** - I just found this answer: https://unix.stackexchange.com/a/339089/393289
It helped me come up with this:
xml ed -d '//configuration/folder[contains(@id,".Folder_A")]' config.xml
I feel like I am closer now. (I tried to upvote that answer but I don't have enough rep yet.) However, I can't translate the attribute name into a bash variable yet due to the quote marks or something else.
BTW, how do I make that perform an in-place edit (similar to the sed -i
command) once I get it working?
Here's an example config.xml file:
basic
0
0
0
false
false
false
25
.stfolder
basic
0
0
0
false
false
false
25
.stfolder
false
true
0
0
0
false
false
true
0
0
0
false
127.0.0.1:8384
98qewr0qe9r
default
0
0
60
false
10
false
-1
3
false
1800
true
false
24
false
5
false
false
10
0
~/Sync/
0
false
auto
0
false
false
This is a config.xml example for syncthing.
Asked by J-S
(43 rep)
Jan 1, 2021, 02:37 AM
Last activity: Feb 27, 2023, 09:04 AM
Last activity: Feb 27, 2023, 09:04 AM