NoWar
NoWar

Reputation: 37632

How to replace part of IP Address in batch file

I would like to replace certain part of IP Address in a batch file.

Lets say there is a variable

set ip=10.20.45.254

or

set ip=10.20.45.2

and i have to change the last part to 1 like

10.20.45.254 -> 10.20.45.1

I have tried to check this manual http://ss64.com/nt/syntax-replace.html but I am not sure how to detect exactly the last part of IP because it can have different length...

Is it possible todo?

Upvotes: 0

Views: 761

Answers (3)

Aacini
Aacini

Reputation: 67236

Simpler:

set ip=10.20.45.254
for %%a in (%ip%) do echo %%~Na.1

This method works also if the IP's are stored as lines inside a file:

for /F %%a in (ipList.txt) do echo %%~Na.1

Upvotes: 1

TangKe
TangKe

Reputation: 378

Try this in batch (replace test.txt with your file name)

for /F "tokens=1,2,3,4 delims=." %%a in (test.txt) do (echo %%a.%%b.%%c.1)

P.S. Try this...

rem -----------------------------------------
rem  Imagine that %line has some IP string...
SET  _IP=%line:~4% 
ECHO IP: %_IP%         
rem -----------------------------------------
timeout /t 2
for /f "tokens=1,2,3,4 delims=." %%a IN ("%_IP%") DO ( 
set gate=%%a.%%b.%%c.1 
)
ECHO Gateway IP: %gate%    

Take care of the qoutes, they are essential ("%_IP%").

Upvotes: 2

7th Luke
7th Luke

Reputation: 87

You can use this to enter in an IP address that you want with a subnet mask of 255.255.255.0.

@echo off 
echo "Enter Static IP" 
echo "Static IP Address:" 
set /p IP_Addr=

netsh interface ip set address <Name of Network Adapter> static %IP_Addr% 255.255.255.0

You can always add in a section to ask for subnet, or just hard code it.

Upvotes: -2

Related Questions