Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a substring from a Windows batch variable

In a batch file I have a variable containing an IP. Just for example:

SET ip = 170.150.120.10

I would like to define another variable, replacing the last octet with 1, which in the example would be 170.150.120.1.

The IP may change (it is defined dynamically), varying in its length, so capturing a fixed length substring and concatenating it would not work anytime (in the example it would be SET baseIP = %ip:~0,9%.1).

How can this task be solved?
Is there some RegEx support in Windows command line?

like image 410
yodabar Avatar asked Aug 18 '15 16:08

yodabar


2 Answers

maytham-ɯɐɥıλɐɯ has the key component of a simple solution - FOR /F. But that solution has a lot of complication that seems unrelated to the question.

The answer can be as simple as:

@echo off
set "ip=170.150.120.10"
for /f "tokens=1-3 delims=." %%A in ("%ip%") do set "new_ip=%%A.%%B.%%C.1"
echo new ip=%new_ip%


Note - You included spaces before and after the = in the SET statement in your question. That is a bad idea, as all of the spaces are significant. You have a variable name that ends with a space, and a value that begins with a space. I removed the unwanted spaces from the answer

Also, I enclosed the assignment within quotes. All characters after the last quote are ignored as long as the first quote is before the variable name. This protects against inadvertent trailing spaces in your value.

EDIT 2017-09-04
Even simpler method - treat the address as a filename, so the last node becomes the extension. Use a simple FOR and the ~n modifier to get the base name (1st 3 nodes), and then add your own extension (last node).

for %%A in (%ip%) do set "new_ip=%%~nA.1"
like image 134
dbenham Avatar answered Oct 31 '22 16:10

dbenham


(Edit: added missing jump)

Here's my take. Iterates over the last four characters, looks if it is a dot, and appends the desired octet to the corresponding prefix part of the given IP. This works with any size (length) of last octet, e.g. 1.1.1.5 and 10.0.0.155

@ECHO OFF
SETLOCAL EnableDelayedExpansion
SET ip=170.150.120.10
SET new_ip_last_octet=1
ECHO Input was %ip%

FOR /L %%G IN (0,-1,-4) DO (
    SET tmp=!ip:~%%G!
    IF "!tmp:~0,1!" == "." (
        SET new_ip=!ip:~0,%%G!.!new_ip_last_octet!
        GOTO done
    )
)
:done
ECHO New IP is %new_ip%

Output:

Input was 170.150.120.10
New IP is 170.150.120.1
like image 2
zb226 Avatar answered Oct 31 '22 14:10

zb226