Tuesday, February 26, 2019

batch rename - How to add a prefix to all folders and sub-folders? (windows)


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.


Answer



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)


No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...