Search code examples
batch-filefor-looprenamedosprefix

Rename Files Based On Folder Name


I am using the following script to rename (prefix) files in subfolders with the string "Application".

pushd "%temporarydirectory%"
for /r %%j in (*) do (
rename "%%j" "Application - %%~nxj"
)
Popd

For example files in:

C:\temp\Lodgements\10 Smith Street

10001.doc
10002.doc

Are renamed to:

Application - 10001.doc
Application - 10002.doc

What I would like to do is to change the script so that files are renamed (prefixed) with the name of the folder in which they are contained. For example files in:

C:\temp\Lodgements\10 Smith Street

10001.doc
10002.doc

Are renamed to:

10 Smith Street - 10001.doc
10 Smith Street - 10002.doc

Regards

george Mackenzie kitten


Solution

  • pushd "%temporarydirectory%" && (
        for /r /d %%a in (.) do for %%b in ("%%~fa\*") do (
            echo ren "%%~fb" "%%~nxa - %%~nxb"
        rem Magoo's tickle begin
        echo "%%~nxb"|FINDSTR /l /c:"%%~nxa - " >NUL&IF ERRORLEVEL 1 echo ren "%%~fb" "%%~nxa - %%~nxb"
        rem Magoo's tickle end
        )
    )
    

    For each folder, for each file inside this folder, rename the file to the name and extension of the folder followed by the name and extension of the file

    (noting that the rename / ren command is simply echoed for deomstration)

    Magoo's tickle: Extends the proposed answer by removing the possibiity that a file named "10 Smith Street - 10001.doc" would be re-renamed "10 Smith Street - 10 Smith Street - 10001.doc" if the procedure was run more than once...