Display First and Last string entries stored in a variable using windows cmd.exe

172 Views Asked by At

I have a variable(MyVar) with values stored in it. For example -->

MyVar="123, 234, 345, 456"

Each entry in the variable is separated by a coma as in the example. I want to be able to pick the first and last entry from this variable, i.e 123 and 456 respectively.

Any idea how I can achieve this using windows cmd.exe ?

Thanks!

2

There are 2 best solutions below

2
On BEST ANSWER
set "first="
set "last="
for %%a in (%myvar%) do set "last=%%a"&if not defined first set "first=%%a"
echo first=%first% last=%last%
0
On

If they are always numbers greater than zero and not
led by zero you can use set /a and variables substrings:

set MyVar="123, 234, 345, 456"

set /a "First=%MyVar:"=%"
for %%i in (%MyVar:"=%)do set "Last=%%i"

echo=%First% %Last%

If the values ​​are alphanumeric and there may set starting with zero and/or led by zero

@echo off 

set MyVar="A01, 234, 345, 0X6"

for /f delims^=^"^, %%i in ('
echo\%MyVar%')do set "First=%%i" & (
for %%i in (%MyVar:"=%)do set "Last=%%~i")

echo=%First% %Last%