Batch scripting: variable in a nested FOR /R loop

2019-08-20 06:43发布

问题:

I am new to batch scripting and the task of writing nested loops and variable expansion in them puzzles me! I need to achieve a simple task in my script:

DIRECTORIES is a list of directory names, generated elsewhere. It can look like a string: "dir1,dir2,dir3".

There's also LOCATION variable, that is set before.

I need to iterate through directory names and do some work with them (omitted here).

One of the tasks if to rename all text files in %LOCATION%\ (currently .txt) to .bbb (but not to touch those ones, that are named 'dir' or "one".

I have created this script. But it doesn't work as supposed. It works well without the outer loop, but I guess something goes wrong with variable name expansion when %%a meets %%b in the nested loop's definition.

for %%a in (%DIRECTORIES%) do (
    ... [do some work]

    :: Rename all .txt files to .bbb (except one.txt and __two__.txt)
    for /r %LOCATION%\%%a %%b in (*.txt) do (
        (Echo "%%b" | FINDSTR "dir __one__" 1>NUL) || (
            ren "%%b" "%%~nb.bbb"
        )
    )
)