在Batch中读取带有特殊字符的文件

时间:2012-06-09 22:04:32

标签: batch-file for-loop io special-characters

如何在Batch中读取和解析带有特殊字符的文件?我有一个名为test.txt的文本文件只有foo!!!bar和一个批处理文件:

@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

我希望并希望以某种方式输出foo!!!bar,但这会输出:

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

当然我只能type test.txt,但我想处理文件的每一行。

1 个答案:

答案 0 :(得分:5)

您的问题是批处理解析器及其阶段的副作用。

在延迟扩展阶段扩展之前,FOR参数会被扩展 但是当%%afoo!!bar时,延迟扩展会删除感叹号,因为!!不是有效的变量扩展。

您需要切换延迟扩展,因为%%a的扩展只有在禁用延迟扩展时才是安全的。

@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
)

您还可以查看How does the CMD.EXE parse...