Search code examples
windowsfilebatch-filebatch-rename

How to add and remove postfix for all files in folder using BATCH File


I'm trying to add and remove postfix from specific file types in all folders and subfolder.
I know the code for adding prefix but I don't know the code for postfix

Here is my code for prefix

Adding PreFix:

@echo off
pushd "D:\Temp\Test\"
for /F "delims=" %%j in ('dir /s /b *.avi *.mkv *.mp4 *.wmv *.mpeg *.flv *.dat *.mov *.asf *.3gp *.srt') do (
   rename "%%j" "[my.prefix]-%%~nxj"
)
popd

Removing PreFix:

@echo off
pushd "D:\Temp\Test\"
for /F "delims=" %%a in ('dir /s /b *.avi *.mkv *.mp4 *.wmv *.mpeg *.flv *.dat *.mov *.asf *.3gp *.srt') do (
    set "fname=%%~nxa"
    set "fpath=%%~dpa"
    setlocal enabledelayedexpansion
    set "nname=!fname:~15!"
    ren "!fpath!!fname!" "!nname!"
    endlocal
)
popd

How to do this for postfix?


Solution

  • Add suffix

    @echo off
    pushd "D:\Temp\Test\"
    for /F "delims=" %%j in ('dir /s /b *.avi *.mkv *.mp4 *.wmv *.mpeg *.flv *.dat *.mov *.asf *.3gp *.srt') do (
       rename "%%j" "%%~nj-[my.suffix]%%~xj"
    )
    popd
    

    Remove suffix

    @echo off
    pushd "D:\Temp\Test\"
    for /F "delims=" %%a in ('dir /s /b *.avi *.mkv *.mp4 *.wmv *.mpeg *.flv *.dat *.mov *.asf *.3gp *.srt') do (
        set "fname=%%~nxa"
        setlocal enabledelayedexpansion
        set "nname=!fname:-[my.suffix]=!"
        ren "%%a" "!nname!"
        endlocal
    )
    popd