parse string delimiter semicolon void

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
darioit
Posts: 230
Joined: 02 Aug 2010 05:25

parse string delimiter semicolon void

#1 Post by darioit » 16 Jan 2017 02:53

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

jeb
Expert
Posts: 1055
Joined: 30 Aug 2007 08:05
Location: Germany, Bochum

Re: parse string delimiter semicolon void

#2 Post by jeb » 16 Jan 2017 06:00

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
   
   )
   

darioit
Posts: 230
Joined: 02 Aug 2010 05:25

Re: parse string delimiter semicolon void

#3 Post by darioit » 16 Jan 2017 08:27

Thank you very much, works well

Squashman
Expert
Posts: 4486
Joined: 23 Dec 2011 13:59

Re: parse string delimiter semicolon void

#4 Post by Squashman » 16 Jan 2017 09:08

Also take a look at Dave's ParseCsv.bat

Aacini
Expert
Posts: 1914
Joined: 06 Dec 2011 22:15
Location: México City, México
Contact:

Re: parse string delimiter semicolon void

#5 Post by Aacini » 16 Jan 2017 12:23

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

Post Reply