2

我正在面臨批處理腳本中讀取CSV文件內容的問題。我有一系列的文件說My_A_File.csv, My_B_File.csv ... My_Z_File.csv。我面臨的問題是閱讀其中的特殊字符。因此,想要閱讀delayedexpansion關閉的值。如何使用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

在線路'設置codeval = = ExitCodeAscii',還有一個第二'='我的猜測不旨在在那裏;!我對嗎? – aschipfl

+1

@aschipfl這是一個[特殊變量](http://ss64.com/nt/syntax-variables.html),包含退出代碼ascii字符 – npocmaka

+0

哇,非常有趣,@npocmaka,我沒有意識到這一點! – aschipfl

回答

3

這延遲的擴張應該如何work.However你可以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 
    ) 
) 
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 
    ) 
) 

閱讀