The task can be done with a batch file with following command lines:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
for /F "delims=" %%I in ('dir "%~dp0*-min.*" /A-D /B /S 2^>nul') do (
set "FullFileName=%%I"
set "FileNameOnly=%%~nI"
set "FileExtension=%%~xI"
setlocal EnableDelayedExpansion
if /I "!FileNameOnly:~-4!" == "-min" ren "!FullFileName!" "!FileNameOnly:~0,-4!!FileExtension!"
endlocal
)
endlocal
The twice used negative value -4
must match with the length of the string to remove from the end of the file name left to the file extension. The string -min
has a length of four characters which is the reason for using here twice -4
.
The command DIR executed by a separate command process started by FOR in background with %ComSpec% /c
and the command line between '
appended as additional arguments outputs also file names like Test-File!-min.x.pdf
with full path. For that reason the IF condition makes sure to rename only files of which file name really ends case-insensitive with the string -min
like Test-File!-MIN.pdf
.
Read the Microsoft documentation about Using command redirection operators for an explanation of 2>nul
. The redirection operator >
must be escaped with caret character ^
on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the embedded dir
command line with using a separate command process started in background.
The code works even for files of which fully qualified file name (drive + path + name + extension) contains one or more exclamation marks because of delayed variable expansion is enabled only for the command line which finally renames a file.
The file renaming task can be done faster with permanently enabled delayed variable expansion as long as no file contains anywhere one or more !
in its fully qualified file name.
@echo off
setlocal EnableExtensions EnableDelayedExpansion
for /F "delims=" %%I in ('dir "%~dp0*-min.*" /A-D /B /S 2^>nul') do (
set "FileNameOnly=%%~nI"
if /I "!FileNameOnly:~-4!" == "-min" ren "%%I" "!FileNameOnly:~0,-4!%%~xI"
)
endlocal
This code does not work for renaming Test-File!-MIN.pdf
to Test-File!.pdf
because of !
in file name.
To understand the commands used and how they work, open a command prompt window, execute there the following commands, and read the displayed help pages for each command, entirely and carefully.
call /?
... explains %~dp0
... drive and path of argument 0 which is the full path of the batch file which always ends with a backslash. It is concatenated with the wildcard pattern *-min.*
for that reason without an additional backslash. %~dp0
can be removed to run DIR on current directory and all its subdirectories instead of batch file directory and all its subdirectories.
dir /?
echo /?
endlocal /?
if /?
ren /?
set /?
setlocal /?
See also this answer for details about the commands SETLOCAL and ENDLOCAL.