1

re: How to add a prefix to all files and folders in a folder? (windows)

I am trying to create a .bat file which will rename a predefined folder structure with a project number prefix eg. project name/admin - becomes - 7000-01 project name/7000-01 admin. Here is what I have so far:

@Echo off
pushd
for /d %%g in (*) do ren "%%g" "7000-01 %%g"

Which works only for the top level but I would like it to rename all sub-folders (including those below the 'admin' level in the eg. above.)

I read here - https://ss64.com/nt/for_d.html that using for /d /r should work to recursively rename all sub-folders, but I cannot get it to work.

FYI the pushd is used so the .bat name stays the same.

0

You were so close! The correct command is:

for /r /d %%g in (*) do ren "%%g" "7000-01 %%~ng"

Full explanation:

As you mentioned, you must use for /d /r to work recursively. (https://ss64.com/nt/for_d.html)

Checking the syntax of the ren or rename command reveals that a very specific syntax is required:

>ren /?
Renames a file or files.

RENAME [drive:][path]filename1 filename2.
REN [drive:][path]filename1 filename2.

Note that you cannot specify a new drive or path for your destination file.

Your original command inside the for loop was evaluating to ren "FULL_PATH" "FULL_PATH", and it should actually be ren "FULL_PATH" "SIMPLE_FILE_NAME"

To get the file name without extension or path, use ~n with the variable (https://ss64.com/nt/syntax-args.html)

  • Thank you, that worked perfectly and I think I understand why, bonus! – Will Aug 28 '18 at 8:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.