You can do this in a batch file if you use a feature called "delayed exapansion" that isn't on by default. To switch it on, you need to start cmd.exe with the /v switch:
cmd.exe /v
Once this is on, the following batch script will replace all spaces in %%i with underscores, and spit the result out:
for /f "usebackq tokens=*" %%i in (`dir /b`) do (
set S=%%i
set T=!S: =_!
echo !T!
)
Vauge description...Excluding the for loop itself, the interesting parts of this are:
- String substitution using the
%var:str1=str2%
syntax
- Delayed expansion using
!var!
instead of %var%
First: delayed expansion... without this, the command interpreter (for whatever reason Microsoft decided to code it as) will evaluate all the parameters first, and then run the script: so this version of the script does NOT work:
for /f "usebackq tokens=*" %%i in (`dir /b`) do (
set S=%%i
set T=%S: =_%
echo %T%
)
With this version the variable 'T' is set to the last value of the for loop before the contents of the (...) block actually execute. Which makes no sense to me. So with delayed execution enabled, we can use the delayed execution variable marks, i.e., !var! rather than %var%. Which gives us the right result.
The other clever bit then is the set T=!S: =_!
(which basically says set T to S, replacing every '' ' in S with ''*). Without delayed expansion, this would be written set T=%S: =_%
.