Add folder name to beginning of filename
I have a directory structure as below:
Folder
> SubFolder1
> FileName1.abc
> Filename2.abc
> .............
> SubFolder2
> FileName11.abc
> Filename12.abc
> ..............
> ..........
etc. I want to rename the files inside the subfolders as:
SubFolder1_Filename1.abc
SubFolder1_Filename2.abc
SubFolder2_Filename11.abc
SubFolder2_Filename12.abc
i.e. add the folder name at the beginning of the file name with the delimiter "_
". The directory structure should remain unchanged. Note: Beginning of file name is same. e.g. in above case File*.
I made below Script
for /r "PATH" %%G in (.) do (
pushd %%G
for %%* in (.) do set MyDir=%%~n*
FOR %%v IN (File*.*) DO REN %%v "%MyDir%_%%v"
popd
)
Problem with the above script is that it is taking only one Subfolder name and placing it to the beginning of file name irrespective of the folder.
You can do this in a more user friendly way using ReNamer, with a single renaming rule:
- Insert ":File_FolderName:_" as Prefix (skip extension)
You can also save it as a Preset and use it for command line renaming.
To rename only files in the immediate child folders
@echo off
pushd "Folder"
for /d %%D in (*) do (
for %%F in ("%%~D\*") do (
for %%P in ("%%F\..") do (
ren "%%F" "%%~nxP_%%~nxF"
)
)
)
popd
To recursively rename all files in child folders
@echo off
pushd "Folder"
for /d %%D in (*) do (
pushd "%%D"
for /r %%F in (*) do (
for %%P in ("%%F\..") do (
ren "%%F" "%%~nxP_%%~nxF"
)
)
popd
)
popd
Make sure you only run either script once! You don't want to put multiple prefixes in front of the files :-)
Additional code could be added to make it safe to run multiple times.