Search code examples
windowscmdrename

Windows CMD rename files with numbers to add leading zeroes up to a certain field format length


I have files with filenames as ID numbers, and need to rename them to include leading zeroes on the ID number up to 7 digits long as well as add extra words to the file name, and keep the file extension.

It specifically needs to dynamically add leading zeroes only if it needs to, up to 7, as while most ID numbers are 6 digits and need 1 leading zero some are 5 or less digits long.

For example 123456 needs to be 0123456 and 123 needs to be 0000123.

I'm using CMD as administrator and this simple command below worked fine previously (last year and a couple weeks ago) in adding leading zeroes to fit the format of the ID in question (7-digit number format), but now as of today it doesn't seem to be working. Now it is only renaming it to add "Report" to the file name.

Ren "C:\Users\folder\Reports\???????*.docx" "??????? Report.docx"

Solution

  • Directly in CMD, as per your question, you could try it like this, (noting that I have replaced C:\Users\folder with %UserProfile%):

    For /F "Delims=" %G In ('Dir "%UserProfile%\Reports\*.docx" /A:-D /B /O:N 2^>NUL ^| %SystemRoot%\System32\findstr.exe /I /R "[0123456789][0123456789]*\.docx"') Do @If 1%~nG Lss 10000000 (Set "BaseName=1000000%~nG" & %SystemRoot%\System32\cmd.exe /V /D /C "Echo(Ren "%UserProfile%\Reports\%G" "!BaseName:~-7! Report%~xG"")
    

    If you are satisfied with the output, remove Echo(, for example:.

    For /F "Delims=" %G In ('Dir "%UserProfile%\Desktop\*.docx" /A:-D /B /O:N 2^>NUL ^| %SystemRoot%\System32\findstr.exe /I /R "[0123456789][0123456789]*\.docx"') Do @If 1%~nG Lss 10000000 (Set "BaseName=1000000%~nG" & %SystemRoot%\System32\cmd.exe /V /D /C "Ren "%UserProfile%\Desktop\%G" "!BaseName:~-7! Report%~xG"")