Search code examples
batch-filesubstringquotes

Batch: Find substring with quotes in string


I cannot get this to work. I am reading an XML file line by line and then look at each line if it contains a specific tag <assemblyIdentity name="PostDeploymentAction" version". When I find it, I would modify it and write everything back into a file. However, I can not find the tag since it contains quote marks.

@ECHO OFF
SETLOCAL EnableExtensions EnableDelayedExpansion
....some more code....
SET dllFile=%DestPath%\%ProjectName%.dll.manifest

IF NOT EXIST "%dllFile%" (
   ECHO File %ProjectName%.dll.manifest does not exist^^!
   GOTO ERROR
) ELSE (
   ECHO Modifying %ProjectName%.dll.manifest in directory:
   ECHO %DestPath%

   REM Create a temporary file in the folder, where this batch file is being executed from
   >"temp.xml" (
      FOR /F "usebackq delims=" %%I IN ("%dllFile%") DO (
        SET "line=%%I"

        REM Insert existing line before modification
        SETLOCAL DisableDelayedExpansion
        ECHO %%I
        ENDLOCAL

        REM Find correct version number
        SET "myVariable=<assemblyIdentity name="PostDeploymentAction" version"
        IF not "!line!"=="!line:myVariable=!" (
          echo !line!
        )
        ....some more code....
       )
    )
  )

Whatever escape characters I use, it will not find this particular line (or it finds every line). Everything else in above code works fine - only IF not "!line!"=="!line:myVariable=!" does not. Any help much appreciated.

Thanks


Solution

  • Use another method to compare the strings:

    @echo off
    setlocal enabledelayedexpansion
    ; set "myvariable=<assemblyIdentity name="PostDeploymentAction" version"
    set myvariable
    for /f "delims=" %%a in (test.txt) do (
      echo "%%a"|findstr /c:"!myvariable:"=\"!">nul && (
        echo DEBUG: found %%a
        REM do something special here
      ) || (
        echo %%a
        REM write line unchanged
      )
    )
    

    (you have to escape the doublequotes with findstr; findstr` uses the backslash as escape character)