Search code examples
windowsbatch-filecmdwindows-terminal

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


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!


Solution

  • set "first="
    set "last="
    for %%a in (%myvar%) do set "last=%%a"&if not defined first set "first=%%a"
    echo first=%first% last=%last%