如何替换 Windows 批处理文件中的子字符串
问题描述:
谁能告诉我在 Windows 中使用批处理文件...如何从文件中读取并用字符串替换 string=bath
hello
这样输出就像 hello Ahello Bhello XYZhelloABC
Can anyone tell me using batch file in windows ...how to read from a file and replace string=bath
from file containing=bath Abath Bbath XYZbathABC
with string hello
so that the output is like hello Ahello Bhello XYZhelloABC
答
Expanding from Andriy M,是的你可以从一个文件中做到这一点,即使是多行的
Expanding from Andriy M, and yes you can do this from a file, even one with multiple lines
@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "INTEXTFILE=test.txt"
set "OUTTEXTFILE=test_out.txt"
set "SEARCHTEXT=bath"
set "REPLACETEXT=hello"
for /f "delims=" %%A in ('type "%INTEXTFILE%"') do (
set "string=%%A"
set "modified=!string:%SEARCHTEXT%=%REPLACETEXT%!"
echo !modified!>>"%OUTTEXTFILE%"
)
del "%INTEXTFILE%"
rename "%OUTTEXTFILE%" "%INTEXTFILE%"
endlocal
编辑
感谢 David Nelson,我已经更新了脚本,因此它不再具有硬编码值.
Thanks David Nelson, I have updated the script so it doesn't have the hard coded values anymore.