我有这样格式的文件:
tcpport 1500
webports 1500,1500
tcpclientport 1500
只有当我找到字符串1500
时,我才想用1510
替换webports
。
我在搜索和替换字符串时发现了许多脚本,但它们用另一个字符串替换了所有出现的字符串。这不是我想要的。
如何在Windows批处理文件中做到这一点?
发布于 2022-09-22 12:25:56
Here is an answer
================================
@::-----------------------------------------------------------------------------------
@:: --- Fonction substitute_str
@::-----------------------------------------------------------------------------------
:substitute_str
@echo off
setlocal enableextensions disabledelayedexpansion
set "oldstring=%1" rem string to replace
set "newstring=%2" rem replacing string
set "textFile=%3" rem file where replacement will take place
set "texttosearch=%4" rem string to be present in the line so that replacement could take place.
set "FICWORK=C:\temp\EvoSvgWin.wrk"
set "FICTEMP=C:\temp\EvoSvgWin.out"
for /f "delims=" %%i in ('type %textFile% ^& break ^> %textFile% ') do (
set "line=%%i"
type NUL > %FICTEMP%
echo(!line! > %FICWORK%
type "%FICWORK%" | findstr /I "%texttosearch%" > %FICTEMP%
for %%S in ("%FICTEMP%") do ( @set "size=%%~zS" )
if NOT !size! EQU 0 (
echo(!line:%oldstring%=%newstring%! >> %textFile%
) else (
echo(!line! >> %textFile%
)
endlocal
)
del %FICTEMP% %FICWORK%
EXIT /B 0
==========================================================================
NB : >> %textFile% is necessary because the function can be called many times with the same file so that all replacements could take place in the same.
https://stackoverflow.com/questions/73806698
复制