Batch Script to rename files from folder name; issue with "-"

Viewed 2003

Been using this script for years that I found from here for renaming movie filenames from parent foldernames:

@echo off
for /r /d %%x in (*) do (
 pushd "%%x"
 echo %%x
 for /F %%i in ("%%x") do (
  ren *.mkv "%%~ni.mkv" 2> NUL
  ren *.avi "%%~ni.avi" 2> NUL
  ren *.mp4 "%%~ni.mp4" 2> NUL
 )
 popd
)

So the only issue that I'm having is the parent folder looks like this: MovieFolder-xyz

Running the script, the filename will be: MovieFolder.mp4

the issue here is the "-xyz" gets omitted and I'm too simple minded to figure out how to fix this script so that I don't have to manually rename all the files. Tia!

1 Answers

I'm not sure why you're doing it like that, but for the same task you could do it like this:

@for /r /d %%x in (*) do @(ren "%%x\*.mkv" "%%~nxx.mkv" 2> NUL
    ren "%%x\*.avi" "%%~nxx.avi" 2> NUL
    ren "%%x\*.mp4" "%%~nxx.mp4" 2> NUL)

Or even simpler:

@for /r /d %%x in (*) do @for %%y in (mkv avi mp4) do @ren "%%x\*.%%y" "%%~nxx.%%y" 2> NUL

A proper script would ascertain whether there are more than one of each of those file types in the directory first, to prevent randomly renaming just one of them, or perform some additional scripting to ensure that only a specific one is renamed.

Related