Search code examples
batch-filecmdbatch-rename

Replace file names in folders and subfolders with bat file


This code works when I do it for ONE folder (when I remove /r option before FOR loop), but when I enable /r option, it can see the files, but it can't rename them.

I want to rename the middle of the file from "-24px" to "lol"

@echo on
setlocal enableDelayedExpansion
for /r %%F in (*-24px*) do (
  set filename="%%F"
  ren "!filename!" "!filename:-24px=lol!"
)

As I have mentioned, it can see the file and its' path, but throws syntax error

Output:

(
  set filename="C:\node_project\fold\1-24px1"
  ren !filename! !filename:-24px=lol!
)
The syntax of the command is incorrect.

Solution

  • The reason: ren destination is the filename only - no path. Syntax:

    REN [drive:][path]filename1 filename2
    

    Your !filename! is a full path when you use /R.

    The solution:

    Get the filename.ext with %%~nxF (see for /? to read more about those modifiers) and change the ren syntax accordingly: the full path (source) would then be "%%F" and the destination would be the adapted "!filename!":

    @echo on
    setlocal enableDelayedExpansion
    for /r %%F in (*-24px*) do (
      set filename="%%~nxF"
      ren "%%F" "!filename:-24px=lol!"
    )