Replace a string, in some conditions, in a file

Viewed 30

I have file whose format like this:

tcpport 1500
webports 1500,1500
tcpclientport 1500

I want to replace 1500 by 1510, only when I find the string webports.

I found many scripts on searching and replacing strings, but they replace all the occurrences of a string by another string. That's not what I want.

How can I do that in a Windows batch file?

1 Answers
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.
Related