SoFunction
Updated on 2025-03-09

DOS(bat) string replacement principle

The principle of replacing all "/" in the string "c:/test/1" with "//":

(Suppose the "C:/TEST/1" string already exists in the VAR variable:)

C:/WINDOWS>set "var=C:/TEST/1"

(Replace all the "/" characters in the string in the var variable with "//")

C:/WINDOWS>set "var=%var:/=//%"

(Show contents in the var variable)

C:/WINDOWS>echo %var%
C://TEST//1

The result is: C://TEST//1, all replaced.

Here are some examples given by other netizens

File string replacement

@echo off

echo ***** Replace "abcd" as "ABCD" *****
set strFilePath=C:\Users\Leez\Desktop\TestBat\
set strOld=abcd
set strNew=ABCD

setlocal enabledelayedexpansion
for /f "tokens=*" %%i in (%strFilePath%) do (
  set "var=%%i"
  if not !var!.==. (
    set "var=!var:%strOld%=%strNew%!"
    echo !var!!>>%strFilePath%.bk
  )
)

move /y %strFilePath%.bk %strFilePath%

pause

Example 2:

@echo off 
setlocal enabledelayedexpansion 
set file= 
set /p file= Please enter the file name to operate(Includes extension): 
set "file=%file:"=%" 
for %%i in ("%file%") do set file=%%~fi 
echo. 
set replaced= 
set /p replaced= Please enter what will be replaced soon: 
echo. 
set all= 
set /p all= Please enter a replacement string: 
for /f "delims=" %%i in ('type "%file%"') do ( 
set str=%%i 
set "str=!str:%replaced%=%all%!" 
echo !str!>>"%file%"_tmp.txt 
) 
copy "%file%" "%file%"_bak.txt >nul 2>nul 
move "%file%"_tmp.txt "%file%" 
start "" "%file%"

I'll change it
Change 16 to 17

@echo off 
setlocal enabledelayedexpansion 
set file=c:\Program Files\hndsclient\ds\
set "file=%file:"=%" 
for %%i in ("%file%") do set file=%%~fi 
echo. 
set replaced=16 
echo. 
set all=17
for /f "delims=" %%i in ('type "%file%"') do ( 
  set str=%%i 
  set "str=!str:%replaced%=%all%!" 
  echo !str!>>"%file%"_tmp.txt 
) 
copy "%file%" "%file%"_bak.txt >nul 2>nul 
move "%file%"_tmp.txt "%file%" 
start "" "%file%"