Replace String in .bat file

May 24, 2009 at 02:11:06
Specs: Windows XP
how can i replace every space in a file or variable with an underscore?

See More: Replace String in .bat file

Report •


#1
May 24, 2009 at 03:23:54
@echo off & setLocal EnableDelayedExpansion

set /p str= string ?
set str=!str: =_!
echo !str!


=====================================
If at first you don't succeed, you're about average.

M2


Report •

#2
May 24, 2009 at 03:40:53
do i replace my variable with string?

Report •

#3
May 24, 2009 at 03:48:31
Not sure I'm with you. As written, it asks for a string. You could hardwire it.

Or you can have it process a file:

==============================
@echo off > newfile & setLocal EnableDelayedExpansion

for /f "tokens=* delims= " %%a in (myfile) do (
set str=%%a
set str=!str: =_!
echo !str!>> newfile
)


=====================================
If at first you don't succeed, you're about average.

M2


Report •

Related Solutions

#4
May 24, 2009 at 03:54:42
awesome got it working. thanks dude!

one more question. i have a file with a .w3g extension. How would i replace all the spaces in the file name with underscores and then save the file again?


Report •

#5
May 24, 2009 at 04:39:58
@echo off & setLocal EnableDelayedExpansion

for /f "tokens=* delims= " %%a in ('dir/b "my own.w3g"') do (
set str=%%~Na
set str=!str: =_!
ren "%%a" "!str!%%~Xa"
)


=====================================
If at first you don't succeed, you're about average.

M2


Report •

#6
May 24, 2009 at 05:21:38
thanks, but for some reason when the name has a ! in it it doesn't work.. any1 way to fix this?

Report •

#7
May 24, 2009 at 06:42:10
Some chars, including !, have special meaning in scripts. So we don't waste much more time, how about posting a few filenames.


=====================================
If at first you don't succeed, you're about average.

M2


Report •

#8
May 24, 2009 at 06:59:29
Here's a quick patch-up of M2's script to allow !'s.


@echo off
setlocal disabledelayedexpansion
for /f "tokens=* delims= " %%a in ('dir/b "my own.w3g"') do (
set str=%%~Na
setlocal enabledelayedexpansion
set str=!str: =_!
ren "%%a" "!str!%%~Xa"
endlocal
)
endlocal


Report •


Ask Question