How to use nested FOR loops in batch files

萝らか妹 提交于 2019-12-07 18:33:52

问题


I have some code in which I want to use a FOR loop to handle a set of files. As part of handling a file there's a FOR /F loop that reads it and appends data to an other file based on the file name.

In order to be able to set the output file name I have delayed variable expansion set on.

This is what the code should look like as I originally intended it to be:

setlocal enabledelayedexpansion
for %%f in (DataFolder\*.Ext) do (
    set POI=%%~f
    set POI=!JbPOI:DataFolder\=!
    set POI=!JbPOI:.Ext=!
    for /f  "tokens=1,2,3 delims=," %%a in ("%%~f") do (
        set CX=%%a
        set CY=%%b
        set FN=%%c
        echo !FN!,9,!CX!,!CY! >> "DataFolder\!POI!.tmp"
    )
)
endlocal

This code doesn't work because variable %%a, %%b and %%c never receive a value, %%a always has the same value as %%f.

I have read some articles about this issue but couldn't extract a solution from them that worked.

I have tried several things, none worked so far...

  • added a dummy outer loop to create variable %%a through %%j explicitly
  • inner FOR loop taken out and made it a subroutine
  • inner FOR loop taken out and made it a separate batch file

Can anybody please tell me how this can - or must - be solved?


回答1:


setlocal enabledelayedexpansion
for %%f in (DataFolder\*.Ext) do (
    set POI=%%~f
    set POI=!JbPOI:DataFolder\=!
    set POI=!JbPOI:.Ext=!
    for /f  "useback tokens=1,2,3 delims=," %%a in ("%%~f") do (
        set CX=%%a
        set CY=%%b
        set FN=%%c
        echo !FN!,9,!CX!,!CY! >> "DataFolder\!POI!.tmp"
    )
)
endlocal

I'm not sure if you want to read the file "%%~f" , but I think this is what you need.




回答2:


Sorry, but for the posted code i don't see the need for delayed expansion. All the needed data is being directly retrieved from the for replaceable parameters

setlocal enableextensions disabledelayedexpansion
for %%f in (DataFolder\*.Ext) do (
  (
    for /f  "usebackq tokens=1-3 delims=," %%a in ("%%~f") do echo(%%c,9,%%a,%%b
  ) > "DataFolder\%%~nf.tmp"
)
endlocal

If the real code includes something not posted, maybe the answer from npocmaka will better fit in the problem.



来源:https://stackoverflow.com/questions/27090735/how-to-use-nested-for-loops-in-batch-files

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