-1

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!

SD4
  • 439
  • 10
  • 27
  • 2
    You need to begin by clarifying the exact value data for your variable, at the moment, it appears that your first entry is `"123`, and your last is `456"`. Then you need to expand upon your code, so that we can see how you're defining that variable content, how you're using it, and what exactly you're wanting to do with the first and last items listed. – Compo Dec 14 '20 at 18:23

2 Answers2

1
set "first="
set "last="
for %%a in (%myvar%) do set "last=%%a"&if not defined first set "first=%%a"
echo first=%first% last=%last%
Magoo
  • 77,302
  • 8
  • 62
  • 84
  • Just for additional clarification, due to my comment under the question proper, in order for `%first%` to contain `123`, and `%last%` to contain `456`, if your variable really does have a value of `"123, 234, 345, 456"`, you'd could to change the code above, from `(%myvar%)` to either `(%myvar:"=%)`, or `(%myvar:~1,-1%)` to get it to work as intended. – Compo Dec 14 '20 at 19:58
  • @Compo : Quite right. I assumed that the string assignment was made using preferred assignment methodology (OP: `set "varname=value"`) where the quotes were not part of the assigned value. – Magoo Dec 14 '20 at 20:40
0

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%
Io-oI
  • 2,514
  • 3
  • 22
  • 29