How to replace all spaces by underscores in all file names of a folder?

Viewed 93645

I'm trying to rename all the files inside a folder (all .exe files). I want to replace all the spaces with underscores, e.g. qwe qwe qwe asd.exe to qwe_qwe_qwe_asd.exe.

I need to do this using the command line. I tried a lot of possible solutions I found on internet and even on this site, but I can't make it work.

I also need to do this in "one single line" / "one command", but I'll accept all the working answers.

8 Answers

Save the following 2 commands in a .bat file. It will replace " " with "_" in all files and folders, recursively, starting from the folder where the file is stored.

forfiles /s /m *.* /C "cmd /e:on /v:on /c set \"Phile=@file\" & if @ISDIR==FALSE ren @file !Phile: =_!"
forfiles /s /C "cmd /e:on /v:on /c set \"Phile=@file\" & if @ISDIR==TRUE ren @file !Phile: =_!"

Note: First line is doing this for files, and second one is doing this for folders. Each line can be used separately.

Minor tweak to Hamza Rashid's answer. Specifically his recursive.bat script.

recursive.bat

set orig=%cd%

for /d /r . %%D in (*) do (
    copy replace.bat "%%D\replace.bat"
    cd "%%D"
    replace.bat
    del replace.bat
    cd %orig%
)

replace.bat stays the same and the instructions stay the same.

Related