Rename all files in a directory with a Windows batch script

后端 未结 2 431
温柔的废话
温柔的废话 2020-11-29 05:17

How would I write a batch or cmd file that will rename all files in a directory? I am using Windows.

Change this:

750_MOT_Forgiving_120x90.jpg
751_MO         


        
2条回答
  •  一生所求
    2020-11-29 05:54

    As of Windows 7 you can do this in one line of PowerShell.

    powershell -C "gci | % {rni $_.Name ($_.Name -replace '120x90', '67x100')}"
    

    Explanation

    powershell -C "..." launches a PowerShell session to run the quoted command. It returns to the outer shell when the command completes. -C is short for -Command.

    gci returns all the files in the current directory. It is an alias for Get-ChildItem.

    | % {...} makes a pipeline to process each file. % is an alias for Foreach-Object.

    $_.Name is the name of the current file in the pipeline.

    ($_.Name -replace '120x90', '67x100') uses the -replace operator to create the new file name. Each occurrence of the first substring is replaced with the second substring.

    rni changes the name of each file. The first parameter (called -Path) identifies the file. The second parameter (called -NewName) specifies the new name. rni is an alias for Rename-Item.

    Example

    $ dir
     Volume in drive C has no label.
     Volume Serial Number is A817-E7CA
    
     Directory of C:\fakedir\test
    
    11/09/2013  16:57              .
    11/09/2013  16:57              ..
    11/09/2013  16:56                 0 750_MOT_Forgiving_120x90.jpg
    11/09/2013  16:57                 0 751_MOT_Persecution_1_120x90.jpg
    11/09/2013  16:57                 0 752_MOT_Persecution_2_120x90.jpg
                   3 File(s)              0 bytes
                   2 Dir(s)  243,816,271,872 bytes free
    
    $ powershell -C "gci | % {rni $_.Name ($_.Name -replace '120x90', '67x100')}"
    
    $ dir
     Volume in drive C has no label.
     Volume Serial Number is A817-E7CA
    
     Directory of C:\fakedir\test
    
    11/09/2013  16:57              .
    11/09/2013  16:57              ..
    11/09/2013  16:56                 0 750_MOT_Forgiving_67x100.jpg
    11/09/2013  16:57                 0 751_MOT_Persecution_1_67x100.jpg
    11/09/2013  16:57                 0 752_MOT_Persecution_2_67x100.jpg
                   3 File(s)              0 bytes
                   2 Dir(s)  243,816,271,872 bytes free
    

提交回复
热议问题