Batch append to end of a file name before the extension with ren command

batch-renamecommand line

I would like to rename all files in a folder, which have different extensions, to have their file name end with "_1" while preserving the existing extensions.

I tried ren * *_1*, which just replaced the last instance of an already-existing underscore in the same to be _1. I also tried ren * *_1.*, but this added _1 to the end of file names.

I'm using the command line (typing cmd from the folder search bar) in Windows 10.

Best Answer

You can use a for loop to iterate each file in a directory and specify the variable substitutions individually to get the name of the file minus the extension and the file extension plus the preceding dot. You can use those and add in the _1 string to get the expected output per each file iterated.

Essentially this. . .

  • Iterates all *.* files in a specific directory (not recursively)
  • Uses variable substitutions for getting the file name without the extension and the file extension separately/individually
  • Concatenates the file name with no extension to the _1 string to the original "." extension and passes that per file as the second argument to the ren command.

Command Line

for %a in ("C:\path\*.*") do ren "%~a" "%~Na_1%~Xa"

Batch Script

SET "Src=C:\path"
SET "Str=_1"
for %%a in ("%Src%\*.*") do ren "%%~a" "%%~Na%Str%%%~Xa"

Further Resources

FOR

  • Variable Substitutions (FOR /?)

    In addition, substitution of FOR variable references has been enhanced. You can now use the following optional syntax:

    %~I         - expands %I removing any surrounding quotes (")
    %~nI        - expands %I to a file name only
    %~xI        - expands %I to a file extension only
    
  • Ren

  • Variable Substitutions
Related Question