Search code examples
batch-filefile-renamebatch-rename

Batch rename specific files adding char to filename


I want to add "a" to specific place in a filename for some, but not all files in a dir.

The files are all pdf files, and have different numbers as filename with the following formats:
x.pdf
or
x_x.pdf

x can range from 1-999. The files to be renamed are all files that has 2 or 3 chars after a "_". The new filename should have a "a" after the _
In this example, bold files should be have a "a" after the _

0.pdf
0_34.pdf
10.pdf
10_1.pdf
10_10.pdf
10_111.pdf

Im trying to do something like IF exist *_??.pdf ren *_a??.pdf (
or creating a loop for %%o in (*_??.pdf) do ren "%%o" "*_a??.pdf"
and then do one with three ???. It doesn't look like im very close, and therefor I ask you guys for help! :)


Solution

  • You could try the following code:

    for /F "eol=| tokens=1,* delims=_" %%E in ('
        dir /B /A:-D "?*_??*.pdf" ^| findstr /I /R /C:"^[0-9][0-9]*_[0-9][0-9][0-9]*\.pdf$"
    ') do (
        ECHO ren "%%E_%%F" "%%E_a%%F"
    )
    

    Here I am using for /F rather than a standard for loop because the directory content is modified while the loop iterates, which could cause trouble, according to this: At which point does for or for /R enumerate the directory (tree)?. With for /F parsing the output of dir /B, the directory content is read before any items are renamed.

    The findstr command line constitutes an additional filter here, so only files following your naming rules are affected by the rename. Remove the findstr command and ^| if you do not want that.

    For testing purposes I added ECHO to the ren command, hence to rename any files, remove it.