5

My question is similar to sed - Delete XML node containing certain element - Unix & Linux Stack Exchange. 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 <folder> 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 <folder> 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|(<folder.*?</folder>)|$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:

    <?xml version="1.0"?>
    <configuration version="32">
        <folder id=".Folder_A" label=".Folder_A" path="~/Sync/.Folder_A" type="sendreceive" rescanIntervalS="3600" fsWatcherEnabled="true" fsWatcherDelayS="10" ignorePerms="false" autoNormalize="true">
            <filesystemType>basic</filesystemType>
            <device id="123ABC" introducedBy="">
                <encryptionPassword/>
            </device>
            <device id="987ZYX" introducedBy="">
                <encryptionPassword/>
            </device>
            <minDiskFree unit="">0</minDiskFree>
            <versioning>
                    <cleanupIntervalS>0</cleanupIntervalS>
            </versioning>
            <copiers>0</copiers>
            <disableSparseFiles>false</disableSparseFiles>
            <disableTempIndexes>false</disableTempIndexes>
            <paused>false</paused>
            <weakHashThresholdPct>25</weakHashThresholdPct>
            <markerName>.stfolder</markerName>
        </folder>
        <folder id=".Folder_B" label="Corporate (.Folder_B)" path="~/Sync/.Folder_B" type="sendreceive" rescanIntervalS="3600" fsWatcherEnabled="true" fsWatcherDelayS="5" ignorePerms="true" autoNormalize="false">
            <filesystemType>basic</filesystemType>
            <device id="123ABC" introducedBy="">
                <encryptionPassword/>
            </device>
            <device id="987ZYX" introducedBy="">
                <encryptionPassword/>
            </device>
            <minDiskFree unit="">0</minDiskFree>
            <versioning>
                    <cleanupIntervalS>0</cleanupIntervalS>
            </versioning>
            <copiers>0</copiers>
            <disableSparseFiles>false</disableSparseFiles>
            <disableTempIndexes>false</disableTempIndexes>
            <paused>false</paused>
            <weakHashThresholdPct>25</weakHashThresholdPct>
            <markerName>.stfolder</markerName>
        </folder>
        <device id="123ABC" name="laptop" compression="always" introducer="false" skipIntroductionRemovals="false" introducedBy="">
            <paused>false</paused>
            <autoAcceptFolders>true</autoAcceptFolders>
            <maxSendKbps>0</maxSendKbps>
            <maxRecvKbps>0</maxRecvKbps>
            <maxRequestKiB>0</maxRequestKiB>
            <untrusted>false</untrusted>
        </device>
        <device id="987ZYX" name="desktop" compression="always" introducer="false" skipIntroductionRemovals="false" introducedBy="">
            <paused>false</paused>
            <autoAcceptFolders>true</autoAcceptFolders>
            <maxSendKbps>0</maxSendKbps>
            <maxRecvKbps>0</maxRecvKbps>
            <maxRequestKiB>0</maxRequestKiB>
            <untrusted>false</untrusted>
        </device>
        <gui enabled="true" tls="true" debugging="false">
            <address>127.0.0.1:8384</address>
            <apikey>98qewr0qe9r</apikey>
            <theme>default</theme>
        </gui>
        <ldap/>
        <options>
            <listenAddress></listenAddress>
            <maxSendKbps>0</maxSendKbps>
            <maxRecvKbps>0</maxRecvKbps>
            <reconnectionIntervalS>60</reconnectionIntervalS>
            <relaysEnabled>false</relaysEnabled>
            <relayReconnectIntervalM>10</relayReconnectIntervalM>
            <startBrowser>false</startBrowser>
            <urAccepted>-1</urAccepted>
            <urSeen>3</urSeen>
            <urUniqueID/>
            <urPostInsecurely>false</urPostInsecurely>
            <urInitialDelayS>1800</urInitialDelayS>
            <restartOnWakeup>true</restartOnWakeup>
            <upgradeToPreReleases>false</upgradeToPreReleases>
            <keepTemporariesH>24</keepTemporariesH>
            <cacheIgnoredFiles>false</cacheIgnoredFiles>
            <progressUpdateIntervalS>5</progressUpdateIntervalS>
            <limitBandwidthInLan>false</limitBandwidthInLan>
            <overwriteRemoteDeviceNamesOnConnect>false</overwriteRemoteDeviceNamesOnConnect>
            <tempIndexMinBlocks>10</tempIndexMinBlocks>
            <trafficClass>0</trafficClass>
            <defaultFolderPath>~/Sync/</defaultFolderPath>
            <maxFolderConcurrency>0</maxFolderConcurrency>
            <crashReportingEnabled>false</crashReportingEnabled>
            <databaseTuning>auto</databaseTuning>
            <maxConcurrentIncomingRequestKiB>0</maxConcurrentIncomingRequestKiB>
            <announceLANAddresses>false</announceLANAddresses>
            <sendFullIndexOnUpgrade>false</sendFullIndexOnUpgrade>
        </options>
    </configuration>

This is a config.xml example for syncthing.

1
  • In-place edits are rarely actually what they seem, so don't worry if a given command doesn't have an option to handle it directly. They're usually something like editor-command file >file.tmp && mv -f file.tmp file Commented May 2, 2021 at 19:59

2 Answers 2

4

Use the -L / --inplace option (see xmlstarlet edit --help) and the exact match from the linked answer:

xmlstarlet ed -L -d "//configuration/folder[@id=\"$foldername\"]" config.xml
1

Using xq (part of yq from https://kislyuk.github.io/yq/):

xq -x --arg id "$foldername" 'del(.configuration.folder[] | select(."@id" == $id))' config.xml

Use the -i or --in-place option to make an in-place edit.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.