Based on this stackhowto, https://stackhowto.com/batch-file-to-list-folder-names/ , I tried to write a batch script that goes through all subfolders of a folder and renames .txt files based on the original folder name. However, I can't seem to actually store the name of the original folder and pass it along to rename the files, even though I can print them out directly just fine using echo %%~nxD. My dummy folder structure looks like this:
Folder subfolder subsubfolder test.txt Where my batch script sits in the Folder.
The script I tried to use is pasted below. It is supposed to run from within the Folder, go into each subfolder, save that subfolders name, then go into each subfolder within that subfolder, and rename any text files that contain the pattern by adding the subfoldername before the pattern in the filename.
However, the subfolder name is not properly saved, instead, what is returned from the echo %replace% is an empty string, and that is what the test.txt file will be renamed to: ".txt".
If I just type
echo %%~nxD the folder name gets printed out correctly as expected, so it's the saving that isn't working
If I just add
set "replace=thisworksfine_%pattern%" right at the beginning of this script after set "pattern=test", then the file will be renamed into "thisworksfine_test.txt" as expected, so normal saving of a parameters works fine.
So clearly I am not understanding how one can save a variable in such a manner using these loops through folders.
Any help would be greatly appreciated!
setlocal enabledelayedexpansion @echo off set "pattern=test" for /d %%D in (*) do ( cd %%~nxD set "replace=%%~nxD_%pattern%" echo %replace% for /d %%D in (*) do ( cd %%~nxD for %%I in (*.txt) do ( set "file=%%~I" ren "%%I" "!file:%pattern%=%replace%!" ) ) cd .. ) cd ..
replaceis undefined at the start of theouterfor/D, %replace% will be *nothing* throughout the code block. You are attempting to usefor...%%D` withinfor...%%D- how iscmdsupposed to determine which%%Dyou mean? Change one of them. Prefer to avoid ADFNPSTXZ (in either case) as metavariables (loop-control variables) as ADFNPSTXZ are metavariable-modifiers which can lead to difficult-to-find bugs (Seefor/ffrom the prompt for documentation)echo %replace%doesn't work, outputtingECHO IS OFF, because that should read asecho !replace!. The next issue with your code is once again because%replace%is used without delaying it. However, you cannot just change that to!replace!because it is nested within another delayed variable. You will therefore need to introduce another layer of delayed expansion, or find an alternative way without it.replaceis%%~nxD_%pattern%, then use%%~nxD_%pattern%in place of%replace%in you string-substitution command.