Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a string and loop through the variables

Tags:

batch-file

I am having a string of format 101514,101234,101645,101798. I want to split the string on , and then loop through each of the individual elements comparing that element with the required value.

set required_value=1024
for /f  "delims=," %%a in ("101514,101234,101645,101798") do (
    set found=%%a
    if "%found%"=="%required_value%" (
        echo true
    ) else (
        echo false
    )
)

Here obviously, only first part is considered. I can use "tokens=1,2,3" and then %%a, %%b, %%c so on to compare, but the length is not fixed.

Is there any other way to solve it.

like image 389
Sid ABS Avatar asked Sep 19 '26 13:09

Sid ABS


2 Answers

I suggest a different method without a loop.

@echo off
setlocal EnableDelayedExpansion
set "RequiredValue=1024"
set "ValuesList=101514,101234,101645,101798"
rem Prepend and append a comma on value list.
set "AllValues=,%ValuesList%,"
rem Use substring replacement to find out if the required
rem value is included in list of values or is missing in list.
if "!AllValues:,%RequiredValue%,=!" == "%AllValues%" (
    echo %RequiredValue% not found in %ValuesList%
) else (
    echo %RequiredValue% is included in %ValuesList%
)
endlocal

To understand the commands used and how they work, open a command prompt window, execute there the following commands, and read the displayed help pages for each command, entirely and carefully.

  • echo /?
  • endlocal /?
  • if /?
  • rem /?
  • set /?
  • setlocal /?
like image 92
Mofi Avatar answered Sep 22 '26 10:09

Mofi


  • use plain for without /f "delims"
  • don't quote the string
  • don't assign to found variable, it won't work without delayed expansion inside the loop, use %%a

for %%a in (101514,101234,101645,101798) do (
    if "%%a"=="%required_value%" (
        echo true
    ) else (
        echo false
    )
)
like image 38
wOxxOm Avatar answered Sep 22 '26 12:09

wOxxOm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!