.bat file for renaming multiple folders

后端 未结 5 1616
别那么骄傲
别那么骄傲 2020-12-10 07:12

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 n

5条回答
  •  温柔的废话
    2020-12-10 07:36

    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=*"
    
    • usebackq specifies backquouted string is a command to be evaluated.(Note that the dir command is enclosed within backquotes(`) )
    • tokens=* means to consider each line as a single token and pass to the command

    To list the sub-directories in parent directory, we use the command:-

    dir /ad /b %1
    
    • /ad displays only directories (ignores files)
    • /b displays it in bare format, i.e., only names are returned and date, time and other info are not.
    • %1 is the command line variable referring to parent directory.
    • %%a is the variable which receives the sub-directory name in each iteration. Double percentage symbol is required since we use it in a batch file, otherwise, just one is required (like %a)

    Finally, we specify the action to be performed:-

    ren %1\%%a %%a%2
    
    • %1\%%a constructs absolute path to sub-directory
    • %%a%2 append second command line parameter to original name

    For more info on for command, type following in a command prompt:-

    for /?
    

    For another usage example, refer Loopy loops: The DOS way

提交回复
热议问题