Search code examples
batch-filevbscriptrenamefile-renamebatch-rename

How to change file names to name of directory that they're in?


I have a folder named "Projects". In that folder, I have multiple folders for my music projects, that have different names, and in each one of these I have an FL Studio project file (.flp), along with project's data, like Wave and MP3 files. But all of the FLP files have the default name ("untitled.flp"). Is there a way to change file names to names of directories that they're in?

I thought that I can make a batch or VBS file, but I'm not sure how should I program it.

Pseudo batch code:

:loop
for each "untitled.flp" in "D:\Google Drive\Projects" goto change
exit
:change
set variable="untitled.flp directory"
ren "untitled.flp" %variable%
goto loop

I'm running Windows 10.


Solution

  • @ECHO OFF
    SETLOCAL
    SET "sourcedir=U:\sourcedir"
    FOR /r "%sourcedir%" %%a IN (untitled.flp) DO IF EXIST "%%a" (
     FOR %%s IN ("%%~dpa.") DO ECHO REN "%%a" "%%~nxs.flp"
    )
    
    GOTO :EOF
    

    You would need to change the setting of sourcedir to suit your circumstances.

    The required REN commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO REN to REN to actually rename the files.

    The first for assigns the directoryname from the entire tree to %%a and appends the filename. The if gates out directorynames where the file is absent and the inner if constructs the full pathname of %%a and appends ., treating the entire resultant name as a filename; then the ren command renames the full filename of the file found to the name and extension part of the file's parent directoryname.