Evan
Evan

Reputation: 537

XML string replacement in Windows batch file

I have a xml file with header and footer like:

set "header=<?xml version="1.0" encoding="UTF-8"?><Config   xmlns="http://namespace.com/config" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0">"
set "footer=</Config>"

I want to remove them from the xml file then read in the remaining items in between the header and footer tags.

I've tried to use sed. this works on Linux but don't do anything on Windows

sed -e "s@%header%@@g" -i.backup xmlFile.xml any suggestions?

Upvotes: 0

Views: 1603

Answers (1)

Endoro
Endoro

Reputation: 37569

In Windows you must escape double quotes with a backslash:

@ECHO OFF &SETLOCAL
set "XMLheader=<?xml version=\"1.0\" encoding=\"UTF-8\"?><Config   xmlns=\"http://namespace.com/config\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" version=\"2.0\">"
set "footer=</Config>"
sed "s@%xmlHeader%\|%footer%@@g" file

Example on the command line:

    >type file
    <?xml version="1.0" encoding="UTF-8"?><Config   xmlns="http://namespace.com/config" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0">
    <tag1>info1 changes in the loop</tag1>
    <tag2>info2 changes in the loop</tag2>
    </Config>

    >sed "s@<?xml version=\"1.0\" encoding=\"UTF-8\"?><Config   xmlns=\"http://namespace.com/config\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" version=\"2.0\">\|</Config>@@g" file

    <tag1>info1 changes in the loop</tag1>
    <tag2>info2 changes in the loop</tag2>

Note: the g flag for the s command of sed is not necessary here.

Upvotes: 3

Related Questions