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_q
Simple as:
set filename=qwe qwe qwe asd.exe
set filename=%filename: =_%
Based on @Gray answer, I have extending it to replace filenames recursively in all subdirectories.
File 1: replace.bat
setlocal enabledelayedexpansion
set "pattern= "
set "replace=_"
for %%I in (*.ext) do (
set "file=%%~I"
ren "%%I" "!file:%pattern%=%replace%!"
)
File 2: recursive.bat
for /d /r . %%D in (*) do (
copy replace.bat "%%D\replace.bat"
cd "%%D"
replace.bat
del replace.bat
cd..
)
Files
replace.bat contains script to replace space with underscorerecursive.bat contains script to do recursion in all subdirectoriesHow to use?
replace.bat and recursive.bat in same directory..ext with desired file extension to match (like .mp4) in replace.bat.recursive.bat file.set data=%date:~6,4%%date:~3,2%%date:~0,2%_%time:~0,2%%time:~3,2%%time:~6,2% set data=%data: =0%
Using forfiles:
forfiles /m *.exe /C "cmd /e:on /v:on /c set \"Phile=@file\" & if @ISDIR==FALSE ren @file !Phile: =_!"
Add /s after forfiles to recurse through subfolders.
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.
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.