Search code examples
cmdcommand-linerename

Rename files by CMD keep last 10 characters and remove all starting characters


I have thousands of HTML files names like "jweofimsdkfmoiwe-8592547472.html.tmp" and "jweofimsdkfmoiwe-8592547472.html.readme" I want to rename all files by command and just want last 10 characters and .html like 8592547472.html. I am not expert but by searching I found follwoing command to remove all .tmp and .readme

for /f "delims=." %a in ('dir /b *.html.readme') do ren "%~a.html.readme" "%~a.html"
for /f "delims=." %a in ('dir /b *.html.tmp') do ren "%~a.html.tmp" "%~a.html"

I searched a lot and found many solutions but only for removing starting characters.

REN *.* " *.*" 
FOR %v IN (*.*) DO REN "%v" %v

I want a simple code which rename files and keep last 10 characters and .html will be very nice if it includes removing last .tmp and .readme

How can convert it to use in CMD?
::Extract only the last 10 characters
SET _result=%_test:~-10%
ECHO %_result%          =8592547472

Thanks in advance.


Solution

  • For your provided examples, if you're using Windows Vista or later, (and as long as you don't have any files which have more than those two levels of extension e.g. *.html.readme.ext). The following should rename your *.html files and *.html.ext files, (where .ext is any other valid extension), which are immediately preceded by a string consisting of a hyphen, -, then 10 digits.

    For /F Delims^= %G In ('%__AppDir__%where.exe .:*-??????????.html* 2^>NUL^|%__AppDir__%findstr.exe "[-][0123456789][0123456789][0123456789][0123456789][0123456789][0123456789][0123456789][0123456789][0123456789][0123456789]\.html"') Do @Echo "%~nxG"|%__AppDir__%findstr.exe "\".*[-][0123456789][0123456789][0123456789][0123456789][0123456789][0123456789][0123456789][0123456789][0123456789][0123456789]\.html\"$">NUL&&(Set "_=%~nxG")||(For /F "EOL=?Delims=" %H In ("%~nG")Do @Echo "%~nxH"|%__AppDir__%findstr.exe "\".*[-][0123456789][0123456789][0123456789][0123456789][0123456789][0123456789][0123456789][0123456789][0123456789][0123456789]\.html\"$">NUL&&Set "_=%~nxH")&%__AppDir__%cmd.exe /V/Q/D/C "Ren "%G" "!_:~-15!""
    

    I'm not going to work through it to explain what is happening and how it works, because trying to type all of this in on my mobile has about exhausted my reserves.

    This task has been made more difficult by stipulating "Rename files by CMD" and "rename all files by command" as opposed to a , a potential solution for which, has already been posted.