Batch rename directories (delete suffix) in Windows 10 [closed]

I have been trying to understand Windows batch scripts but the syntax is so very different to modern programming languages that I simply cannot get what I want to do to work. I've also tried googling this and checked SO/SU to no avail.

I have a large number of folders in another folder ("C:\Users\me\Desktop\Delete") that are the contents of downloaded web pages. The format is:

thisIsTheWebPageName_files
thisIsTheWebPageName.html

What I'd like to do in a batch file (note: standard CMD .bat file - not PowerShell) is to iterate over all folders, rename them by simply removing the "_files" suffix, then deleting the associated .html file. I am sure an expert can probably do this in one line - can anyone help?


Solution 1:

Iterate over all files or directories:

for %%i in (*.html) do ...

for /d %%i in (*_files) do ...

Note: In .bat scripts you must use %% for the iterator variable, while the interactive shell uses only a single %.

Remove a file extension (only works with iterators, not variables):

%~ni, %~xi

for %%f in (*.html) do echo %%~nf_files

Replace a substring (only works with named variables, not iterator):

%var:old=new%

ren "%dir%" "%dir:_files=%"

Slice a string (only works with named variables):

%var:~begin,end%

ren "%dir%" "%dir:~0,-6%"

iterate over all folders, rename them by simply removing the "_files" suffix, then deleting the associated .html file

Doing two things at once within the same for loop is possible, but makes the usage of named variables quite annoying, as they're expanded at read time, not at call time. (And we need named variables to remove the "_files" suffix.)

It might be easier to call a subroutine instead:

for /d %%d in (*_files) do call :tidy "%%~d"
goto :eof

:tidy
set "dirname=%~1"
echo Would run: ren "%dirname%" "%dirname:~0,-6%"
echo Would run: del "%dirname:~0,-6%.html"
goto :eof

But if every single *.html file has a corresponding _files directory and vice versa, you could iterate over the files instead:

for %%i in (*.html) do echo ren "%%~ni_files" "%%~ni" && echo del "%%~i"

(I think the && works as intended here. I might do it in two steps instead.)

for %%i in (*.html) do echo ren "%%~ni_files" "%%~ni"
del *.html