DEV Community

Ankur Sheel
Ankur Sheel

Posted on • Originally published at ankursheel.com on

How to rename multiple files in subfolders using Windows command prompt

Problem

As part of the migration from Gatsby to Statiq, I had to rename all the files with the extension mdx to md. Now, I could do it one by one or find a utility but using a single command is more elegant.

Solution

To rename all the files recursively, we can use the REN (rename) command as follows.

FOR /R %G IN (*.mdx) DO REN "%f" "%~dpnG.md"
Enter fullscreen mode Exit fullscreen mode

Let’s unpack this command.

  • FOR : Loops through files
  • /R : Recurse through subfolders.
  • %G : A parameter set to a different value for each iteration of the for loop.
  • (*.mdx): The filename pattern that we want to match.
  • REN : The command to rename a file
  • %~dpnG” : Expands the parameter of the original filename to the fully qualified path without the extension

References:

Top comments (2)

Collapse
 
irljc profile image
JC

FWIW - I had a similar requirement, but struggling with this code not working, changed as below. Then it worked.

FOR /R %G IN (*.png) DO REN "%G" "filename.png"
Enter fullscreen mode Exit fullscreen mode

So, for someone who doesn't understand, what is the "%f" in the example you used and what does it do?

Collapse
 
ankursheel profile image
Ankur Sheel

Yeah. Sorry for the late reply.
This command doesnt work as expected.

I updated the commands you need at the original site ankursheel.com/blog/rename-multipl....