0

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?

3 Answers 3

2

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%").

Sign up to request clarification or add additional context in comments.

6 Comments

Would you mind to change code so it gets IP from some variable, please?
for /? shows you how to: ... in ("%var%") do ...
why should it? The quotes tell for to treat it as text, not as a filename.
@Stephan Look, when I execute only this line of code SET _IP="12.45.2.123" for /f "tokens=1,2,3,4 delims=." %%a IN (%_IP%) DO echo %%a.%%b.%%c.1 pause then it works fine. But when i do the same from more complex batch file it gives message that it cannot find the file and display IP consuming from %_IP%
take care of the qoutes, they are essential. In your question you set ip=10.20.45.254, in your comment you SET _IP="12.45.2.123"
|
1

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

Comments

-2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.