3

How do I read and parse a file with special characters in Batch? I have a text file named test.txt with just foo!!!bar and a batch file with this:

@echo off
setlocal enabledelayedexpansion enableextensions

FOR /F "tokens=* delims=" %%a IN (.\test.txt) DO (
    echo Unquoted is %%a
    echo Quoted is "%%a"
    set "myVar=%%a"
    echo myVar is still !myVar! or "!myVar!"
)
exit /b 0

I want and expect it to output foo!!!bar somehow, but this outputs:

Unquoted is foobar
Quoted is "foobar"
myVar is still foobar or "foobar"

Of course I can just type test.txt, but I want to process each line of the file.

anomal
  • 2,249
  • 2
  • 19
  • 17

1 Answers1

5

Your problem is a side effect of the batch parser and it's phases.

The FOR parameters are expanded just before the delayed expansion phase would be expand.
But when %%a is foo!!bar, then the delayed expansion would remove the exclamation marks, as !! isn't a valid variable expansion.

You need to toggle the delayed expansion, as expanding of %%a is only safe with disabled delayed expansion.

@echo off
setlocal DisableDelayedExpansion enableextensions

FOR /F "tokens=* delims=" %%a IN (.\test.txt) DO (
    echo Unquoted is %%a
    echo Quoted is "%%a"
    set "myVar=%%a"

    setlocal enabledelayedexpansion 
    echo myVar is still !myVar! or "!myVar!"
    endlocal
)

You could also look at How does the CMD.EXE parse...

Community
  • 1
  • 1
jeb
  • 78,592
  • 17
  • 171
  • 225
  • In my case I used same toggle before I write the content into file, but getting error please help me – CIPHER Aug 08 '16 at 11:49