I am trying to write a batch script to rename multiple folders. I would like to do something like below: Rename all folders under the "Workspace" folder by appending my name in the end of the folder names
For example, rename:
Workspace/RiskFolder
Workspace/PNLFolder
to:
Workspace/RiskFolder_myname
Workspace/PNLFolder_myname
Is this possible?
You could use for to loop through each directory and rename it like so:
for /D %%f in (C:\path\to\Workspace\*) do rename "%%f" "%%~nxf_myname"
I tested this on Windows 7, but it should work at least as far back as with Windows XP.
What that does is this: for each directory in the path (within parenthesis), assign the directory name to the variable %%f
, then rename the directory %%f
to the name in the format you want (with your name attached). %%f
holds the full pathname, which is fine for the first argument to the rename
command, but for the second argument, we only want the filename+extension, thus the ~nx modifier prepended to our variable name.
By the way, when using this for
loop on the command line (rather than part of a batch file) you only want to use one % instead of %% for your variable name. E.g. for %f in...
instead of above.
See the following references from Microsoft for more details:
You can use the following command within your batch file:-
for /F "usebackq tokens=*" %%a in (`dir /ad /b %1`) do ren %1\%%a %%a%2
This is the DOS 'for' command, which iterates over given set of items, and for each element in the set, performs the given action. For the given requirement, we need to do the following:-
1) Accept name of folder which contains sub-folders to be renamed(in your example, it is Workspace).
2) Accept the string to be appended to the end(in your example, it is your name).
3) List the names of sub-folders in the folder.
4) Rename by appending the string to original name.
Let's see how this for command accomplishes that. The format of 'for' command used here is:-
for /F ["options"] %variable IN (`command`) do command [command-parameters]
The command here assumes that the required parent directory name and string to be appended are passed on as command line parameters. These are represented by %1 and %2 (first and second parameters).
To enable us to issue a dos command to be evaluated, we need to use the /F option. The option string is :-
"usebackq tokens=*"
To list the sub-directories in parent directory, we use the command:-
dir /ad /b %1
Finally, we specify the action to be performed:-
ren %1\%%a %%a%2
For more info on for command, type following in a command prompt:-
for /?
For another usage example, refer Loopy loops: The DOS way
No need for a batch file. This will work from the command line
for /d %D in ("Workspace\*") do ren "%D" "%~nxD_myName"
If you do use a batch file, then %D
must become %%D
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With