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 ..