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

Adapted from here:

https://stackoverflow.com/a/16129486/2000557

@echo off
Setlocal enabledelayedexpansion

Set "Pattern= "
Set "Replace=_"

For %%a in (*.exe) Do (
    Set "File=%%~a"
    Ren "%%a" "!File:%Pattern%=%Replace%!"
)

Pause&Exit

Create a batch file (*.bat) with the above contents. Place that batch file in the folder with all the .exe's and it will replace the spaces with underscores when you run it.


Simple as:

set filename=qwe qwe qwe asd.exe
set filename=%filename: =_%

A one liner

cmd /e:on /v:on /c "for %f in ("* *.exe") do (set "n=%~nxf" & set "n=!n: =_!" & ren "%~ff" "!n!" )"

Spawn a cmd instance, with extensions and delayed expansion enabled, and for each exe file with spaces in name, replace spaces with underscores and rename the file with the new name