Alex
Alex

Reputation: 72

cmd batch rename subfolders/files

how can i batch rename the files from folder A which contains subfolders and files with this format name filename_ex.doc and make them look like filename.doc?

i've been trying to do this for awhile now and it's been an epic fail. please help.

Upvotes: 3

Views: 3841

Answers (1)

dbenham
dbenham

Reputation: 130819

I presume you want to rename the files in the subfolders as well, which is where you had problems with the direction in your 2nd comment to Martin James. I'm guessing you tried that code with the DIR /S option. But you were so close :-) You just needed to use 2 loops!

Edit - fixed code Once the output looks correct, drop the ECHO to make it functional.

@echo off
for /r %%D in (.) do (
  pushd "%%~fD"
  for /f "tokens=1-3 delims=_." %%A in ('dir /b *_ex.ext 2^>nul') do echo ren "%%A_%%B.%%C" "%%A.%%C"
  popd
)

The above will work as long as each file name does not have any _ or . other than what appears in _ex.ext. Characters in the path should not be any problem, just the file name is a concern.

Here is a more robust solution that should work with any filename (except unicode names). It is also significantly faster. It uses a substring operation, and you must know the number of characters to strip from the name. In your example it is 3 characters. Again, remove ECHO once the resultant commands look correct.

@echo off
setlocal disableDelayedExpansion
for /f "delims=" %%F in ('dir /b /s *_ex.ext') do (
  set "old=%%F"
  set "new=%%~nF"
  setlocal enableDelayedExpansion
  echo ren "!old!" "!new:~0,-3!.ext"
  endlocal
)

Upvotes: 3

Related Questions