在批处理中使用特殊字符读取文件 [英] Reading a file with special characters in Batch

查看:251
本文介绍了在批处理中使用特殊字符读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 @echo off 
setlocal enabledelayedexpansion enableextensions

FOR / Ftokens = * delims =%% a IN(.\test.txt) DO(
echo未加引号是%% a
引用是%% a
setmyVar = %% a
echo myVar is still!myVar!or! myVar!

exit / b 0

我想和期待它以某种方式输出 foo !!! bar ,但是输出:

 无引号的是foobar 
引用是foobar
myVar仍然是foobar或foobar

当然,我可以只用类型t​​est.txt ,但是我想处理文件的每一行。

您的问题是批解析器的一个副作用,它是阶段。

FOR参数在延迟扩展阶段扩展之前被扩展。

但是当 %% a foo !! bar ,那么延迟的扩展将删除感叹号,如 !! 您需要切换延迟扩展,如 %% a 的扩展
只有禁用延迟扩展才是安全的。

  @echo off 
setlocal DisableDelayedExpansion enableextensions

FOR / Ftokens = * delims =%% a IN(.\test.txt)DO(
echo未加引号是%%
引用是%% a
setmyVar = %% a

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

pre>

你也可以看看如何解析CMD.EXE ...


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.

解决方案

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

这篇关于在批处理中使用特殊字符读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆