我在批处理脚本中阅读CSV文件的内容时遇到问题。我有一系列文件说My_A_File.csv, My_B_File.csv ... My_Z_File.csv
。我面临的问题是阅读其中的特殊字符。因此,想要在关闭delayedexpansion的情况下读取值。
当我使用disabledelayedexpansion读取块中的值时,它们是空的!我怎么处理这个?
脚本:
@echo off
setlocal enabledelayedexpansion
for /L %%g in (65,1,90) do (
cmd /c exit /b %%g
set codeval=!=ExitCodeAscii!
set fileToReadFrom=My_!codeval!_File.csv
if exist My_!codeval!_File.csv (
echo Outer-!fileToReadFrom!
echo Outer-!codeval!
setlocal disabledelayedexpansion
echo Inner-%fileToReadFrom%
echo Inner-%codeval%
endlocal
)
)
输出:
Outer-My_A_File.csv
Outer-A
Inner-
Inner-
答案 0 :(得分:3)
延迟扩展应该如何工作。但是你可以使用CALL
来访问变量,但这会影响性能(请注意你不能CALL FOR):
@echo off
setlocal enabledelayedexpansion
for /L %%g in (65,1,90) do (
cmd /c exit /b %%g
set codeval=!=ExitCodeAscii!
set fileToReadFrom=My_!codeval!_File.csv
if exist My_!codeval!_File.csv (
echo Outer-!fileToReadFrom!
echo Outer-!codeval!
setlocal disabledelayedexpansion
call echo Inner-%%fileToReadFrom%%
call echo Inner-%%codeval%%
endlocal
)
)
或者你可以使用pipes.Which也会达到性能(现在你可以使用
break|for "usebackq" %%a in ("Inner-%%fileToReadFrom%%") do @echo %%~a
):
@echo off
setlocal enabledelayedexpansion
for /L %%g in (65,1,90) do (
cmd /c exit /b %%g
set codeval=!=ExitCodeAscii!
set fileToReadFrom=My_!codeval!_File.csv
if exist My_!codeval!_File.csv (
echo Outer-!fileToReadFrom!
echo Outer-!codeval!
setlocal disabledelayedexpansion
break|echo Inner-%%fileToReadFrom%%
break|echo Inner-%%codeval%%
endlocal
)
)
答案 1 :(得分:3)
使用子程序处理禁用延迟扩展的代码,如下所示:
@echo off
rem skip subroutine code
goto :toMain
:toProcessDDE
rem subroutine to process delayed expansion disabled
setlocal disabledelayedexpansion
echo Inner-%fileToReadFrom%
echo Inner-%codeval%
endlocal
exit /B
:toMain
setlocal enabledelayedexpansion
for /L %%g in (65,1,90) do (
cmd /c exit /b %%g
set codeval=!=ExitCodeAscii!
set fileToReadFrom=My_!codeval!_File.csv
if exist My_!codeval!_File.csv (
echo Outer-!fileToReadFrom!
echo Outer-!codeval!
call :toProcessDDE
)
)
读