Batch rename sequential files by padding with zeroes

后端 未结 8 1202
天命终不由人
天命终不由人 2020-12-08 02:42

I have a bunch of files named like so:

output_1.png
output_2.png
...
output_10.png
...
output_120.png

What is the easiest way of renaming t

8条回答
  •  没有蜡笔的小新
    2020-12-08 02:53

    Fairly easy, although it combines a few features not immediately obvious:

    @echo off
    setlocal enableextensions enabledelayedexpansion
    rem iterate over all PNG files:
    for %%f in (*.png) do (
        rem store file name without extension
        set FileName=%%~nf
        rem strip the "output_"
        set FileName=!FileName:output_=!
        rem Add leading zeroes:
        set FileName=000!FileName!
        rem Trim to only four digits, from the end
        set FileName=!FileName:~-4!
        rem Add "output_" and extension again
        set FileName=output_!FileName!%%~xf
        rem Rename the file
        rename "%%f" "!FileName!"
    )
    

    Edit: Misread that you're not after a batch file but any solution in any language. Sorry for that. To make up for it, a PowerShell one-liner:

    gci *.png|%{rni $_ ('output_{0:0000}.png' -f +($_.basename-split'_')[1])}
    

    Stick a ?{$_.basename-match'_\d+'} in there if you have other files that do not follow that pattern.

提交回复
热议问题