Shiva r
Shiva r

Reputation: 5

Batch script to find and replace same string in multiple services in same .ini file

I needed to find and replace the ip address in a .ini file. The issue in my previous question was I only needed to change one IP address within a service. Now, I have the same text variable in different service names under the same .ini file. Below are details.

I have the following.

SERVICE_NAME=Test1 
SERVICE_L2TP_PEER_IPADDRESS=1.1.1.1 
SERVICE_Name=Test2 
SERVICE_L2TP_PEER_IPADDRESS=2.2.2.2 

It’s the same pattern, but different service name in the same file. The script will locate values above and change 1.1.1.1 to 7.7.7.7 and 2.2.2.2 to 8.8.8.8. I require some help in how to define the service to choose, since both text variables are the same.

Below is the post I used before.

Batch script that will allow to search a particular IP and change it to a new IP address in a .ini file

Upvotes: 0

Views: 358

Answers (1)

MichaelS
MichaelS

Reputation: 6032

This will do the job.

@ECHO OFF
SETLOCAL EnableDelayedExpansion
SET iniFile=some.ini
TYPE NUL>temp_file.ini
FOR /F "tokens=*" %%L IN (%iniFile%) DO (
    SET currentLine=%%L
    REM ECHO !currentLine:~0,28!
    IF "!currentLine:~0,28!"=="SERVICE_L2TP_PEER_IPADDRESS=" (
        SET currentLine=!currentLine:1.1.1.1=7.7.7.7!
        SET currentLine=!currentLine:2.2.2.2=8.8.8.8!
    )
    ECHO !currentLine!>>temp_file.ini
)
MOVE /Y temp_file.ini %iniFile%

You'll have to replace some.ini with the proper path and file name of your ini file.

Upvotes: 1

Related Questions