Batch file escaping issues

时间:2019-03-25 16:34:00

标签: batch-file escaping

I've written a batch file to modify the attribute of an XML file. The script works and the attribute if modified, however I'm having an issue with escaping some characters.

I've tried every solution I can possibly find online with no luck.

My intended output is:

<xs:import schemaLocation="2e9dd7db-f58b-4c91-8575-3b3af05d3178.xsd" namespace="urn:verastar:veracore:types" />

However I'm getting:

<xs:import schemaLocation="="2e9dd7db-f58b-4c91-8575-3b3af05d3178.xsd"" namespace="urn:verastar:veracore:types

I've tried escaping the quotes with ^, this works when using echo to the console however doesn;t work when writing to the file.

Why am I getting ="=" also I'm getting double quotes, but when I remove one nothing gets written to the file.. and finally the last quote seems to be messing things up and therefore the output is missing the XML closing tag.

How can I escape these characters properly?

My code is:

@echo on
setlocal EnableExtensions DisableDelayedExpansion

rem check if the XSD to modify exists in the batch directory
set "XSDFile=%~dp0test.xsd"

if not exist "%XSDFile%" goto EndBatch

rem environment variables
set "LineNumber="
set "LineCount=0"
set "TmpFile=%TEMP%\%~n0.tmp"

rem Search for the line containing attribute schemaLocation and get its
rem line number and the line itself loaded into environment variables

for /F "tokens=1* delims=:" %%I in ('%SystemRoot%\System32\findstr.exe /L /N /C:schemaLocation= "%XSDFile%" 2^>nul') do (
    set "LineNumber=%%I"
    set "FileLine=%%J"
)

rem If no line with attribute schemaLocation found, exit this batch file
if not defined LineNumber goto EndBatch

setlocal EnableDelayedExpansion
set "FileName=!FileLine:*schemaLocation=!"

for /f "tokens=1 delims=?" %%a in ("%FileName%") do (set test=%%a)

set "test=<xs:import schemaLocation="%test%.xsd"" namespace="urn:verastar:veracore:types" />"

pause

endlocal & set "FileLine=%test% 

rem Make sure the temporary file used next does not already exist.
del "%TmpFile%" 2>nul

rem Copy all lines from XML file to a temporary file including empty
rem lines with the exception of the line containing attribute schemaLocation
rem which is copied to temporary file with the modified schemaLocation.
for /F "tokens=1* delims=:" %%I in ('%SystemRoot%\System32\findstr.exe /R /N "^" "%XSDFile%" 2^>nul') do (
    set "XmlLine=%%J"
    set /A LineCount+=1
    setlocal EnableDelayedExpansion
    if not !LineCount! == %LineNumber% (
        echo/!XmlLine!>>"%TmpFile%"
    ) else (
        echo/!FileLine!>>"%TmpFile%"
    )
    endlocal
)

rem Overwrite original file with temporary file automatically deleted on success.
move /Y "%TmpFile%" "%XSDFile%" >nul

:EndBatch
endlocal

0 个答案:

没有答案