code'
code'

Reputation: 21

Using Windows Command Line FOR command with quoted commas

I am trying to process a file containing values formatted like this:

 Token1    Token2            Token3    Token4
"ValueA", "ValueB, ValueC", "ValueD", "Value E"

(Headers added by me for clarity). I just want tokens 2 and 4.

The following command:

for /f "tokens=2,4 delims=," %a in (TestSource.txt) do @echo %a %b

Does work, but of course when Token2 contains a comma (as it does in the above example), it gets broken at that comma since the FOR command doesn't seem to know any better.

Are there any known workarounds to this limitation - I did quite a bit of looking into it and saw a "usebackq" command, but I don't think this is what I need.

Thanks!

Upvotes: 2

Views: 338

Answers (1)

MC ND
MC ND

Reputation: 70923

for /f tokens^=3^,7^ delims^=^" %f in (data.csv) do echo "%f", "%g"

There are two ways to include a "options" string for the for command. As it can include spaces and special characters, the first is the usual quoted string. But is some cases, it is not sufficient.

The second way is shown in the included code: escape all the separators in the options string.

Upvotes: 1

Related Questions