Reading a file with special characters in Batch

て烟熏妆下的殇ゞ 提交于 2019-12-10 20:25:40

问题


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.


回答1:


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...



来源:https://stackoverflow.com/questions/10964923/reading-a-file-with-special-characters-in-batch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!