Page 1 of 1

parse string delimiter semicolon void

Posted: 16 Jan 2017 02:53
by darioit
Hello everybody,
I got a new little problem

I try to parse this raw:

Code: Select all

@echo off
setlocal EnableDelayedExpansion

set string=a a;b b;c c;d d;e e;f f;g g;h h;;j;name.pdf
echo list = "%string%"

for /f "tokens=7,8,9,10 delims=;" %%a in ("!string!") do (

    echo Variable  7=%%a
    echo Variable  8=%%b
    echo Variable  9=%%c
    echo Variable 10=%%d
   
   )

Results is:
list = "a a;b b;c c;d d;e e;f f;g g;h h;;j;name.pdf"
Variable 7=g g
Variable 8=h h
Variable 9=j
Variable 10=name.pdf

but when some value is missing "J" as show in this raw
set string=a a;b b;c c;d d;e e;f f;g g;h h;;;name.pdf

results is this
list = "a a;b b;c c;d d;e e;f f;g g;h h;;;name.pdf"
Variable 7=g g
Variable 8=h h
Variable 9=name.pdf
Variable 10=

I expect Variable 9 = nothing
I expect Variable 10 = name.pdf

How can I parse better this raw?

thank you in advance

Re: parse string delimiter semicolon void

Posted: 16 Jan 2017 06:00
by jeb
Hi darioit,

as FOR /F removes empty tokens, I use a trick to avoid empty tokens.
I add quotes before and after each ; and also to the begin and end of the string.
Then all tokens are surrounded by quotes, they can be simply removed with %%~

Code: Select all

echo off
setlocal EnableDelayedExpansion

set string=a a;b b;c c;d d;e e;f f;g g;h h;;j;name.pdf
echo list = "%string%"

set "QString="!string:;=";"!""
for /f "tokens=7,8,9,10 delims=;" %%a in ("!Qstring!") do (

    echo Variable  7=%%~a
    echo Variable  8=%%~b
    echo Variable  9=%%~c
    echo Variable 10=%%~d
   
   )
   

Re: parse string delimiter semicolon void

Posted: 16 Jan 2017 08:27
by darioit
Thank you very much, works well

Re: parse string delimiter semicolon void

Posted: 16 Jan 2017 09:08
by Squashman
Also take a look at Dave's ParseCsv.bat

Re: parse string delimiter semicolon void

Posted: 16 Jan 2017 12:23
by Aacini

Code: Select all

@echo off
setlocal EnableDelayedExpansion

set string=a a;b b;c c;d d;e e;f f;g g;h h;;j;name.pdf
echo list = "%string%"

set "i=1"
set "var[!i!]=%string:;=" & set /A i+=1 & set "var[!i!]=%"

echo Variable  7=%var[7]%
echo Variable  8=%var[8]%
echo Variable  9=%var[9]%
echo Variable 10=%var[10]%

Output:

Code: Select all

list = "a a;b b;c c;d d;e e;f f;g g;h h;;j;name.pdf"
Variable  7=g g
Variable  8=h h
Variable  9=
Variable 10=j

See this thread.

Antonio