The following batch file can be used if there is always just one hyphen between the file name part to remove and the file name part to keep.
@echo off
setlocal EnableExtensions DisableDelayedExpansion
for /F "eol=| delims=" %%I in ('dir *.html.readme *.html.tmp /A-D /B 2^>nul') do for /F "eol=| tokens=1* delims=-" %%J in ("%%~nI") do ren "%%I" "%%K"
endlocal
The inner FOR processes the file name string without extension .readme
or .tmp
and assigns everything left to first (series of) -
to specified loop variable J
(not further used) and everything after first (series of) -
to next but one loop variable K
according to the ASCII table. Hyphens at beginning of a file name are removed before assigning first hyphen delimited substring to not used loop variable J
.
Otherwise the following batch file could be used for this file renaming task with file names containing inside more than one hyphen:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
for /F "eol=| delims=" %%I in ('dir *.html.readme *.html.tmp /A-D /B 2^>nul') do (
set "SourceFileName=%%I"
for %%J in ("%%~nI") do set "TargetFileName=%%~nJ"
setlocal EnableDelayedExpansion
set "TargetFileName=!TargetFileName:~-10!"
ren "!SourceFileName!" "!TargetFileName!.html"
endlocal
)
endlocal
Please read this answer for details about the commands SETLOCAL and ENDLOCAL. It is necessary to enable/disable delayed expansion inside the FOR loop as otherwise it would not be possible to process file names correct containing one or more exclamation marks.
This batch file really uses always the last 10 characters of the source file name for the target file name.
The following batch file can be used if there is guaranteed that no file to rename contains one or more !
in its name.
@echo off
setlocal EnableExtensions EnableDelayedExpansion
for /F "eol=| delims=" %%I in ('dir *.html.readme *.html.tmp /A-D /B 2^>nul') do (
for %%J in ("%%~nI") do set "TargetFileName=%%~nJ"
ren "%%I" "!TargetFileName:~-10!.html"
)
endlocal
One more solution similar to above working for file names with one or more exclamation marks by not using delayed expansion, but use command CALL to double parse the command line with command REN before execution of the rename command.
@echo off
setlocal EnableExtensions DisableDelayedExpansion
for /F "eol=| delims=" %%I in ('dir *.html.readme *.html.tmp /A-D /B 2^>nul') do (
for %%J in ("%%~nI") do set "TargetFileName=%%~nJ"
call ren "%%I" "%%TargetFileName:~-10%%.html"
)
endlocal
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 /?
dir /?
echo /?
endlocal /?
for /?
ren /?
set /?
setlocal /?