0

I have the following code:

set "x=c:\aa;c:\bb;c:\c c"

for %%g in (%x%) do (
    echo %%g
)

It outputs:

c:\aa
c:\bb
c:\c
c

It interprets the space as delimiter. But I don't want this. Only the semicolon should be a valid separator. Thee output should be:

c:\aa
c:\bb
c:\c c

It should work for any number of entries. I found solutions, but they where quite complicated. I'm looking for a simple solution, if there's any. The list can have another format if needed.

Martin Fehrs
  • 792
  • 4
  • 13
  • 3
    Use string substitution to double quote all semicolon separated elements => `for %%g in ("%x:;=";"%") do echo %%~g` –  Sep 06 '19 at 09:16
  • It works. If I understood it correctly, this produces "c:\aa""c:\bb""c:\c c". I really have a hard time to undersand the quoting rules of batch scripts. Do you know a good source for this topic? – Martin Fehrs Sep 06 '19 at 09:24
  • 2
    no, it produces ` "c:\aa";"c:\bb";"c:\c c"` - three quoted strings delimited by `;`. Quoting is required, when a string contains a space (but it's much easier to quote all of them instead of checking if there is a space and only quote if yes) – Stephan Sep 06 '19 at 09:27
  • It is indeed a duplicate. The linked question already contains the answer. – Martin Fehrs Sep 06 '19 at 09:30
  • 2
    `%x%`is enclosed in outer double quotes and the semicolons themselves are replaced with `";"`. On output use the tilde `~` to strip the double quotes. In general cmd supports only double quotes to *hide* content (poisenous chars like `<>|&`) from being interpreted directly, aside from escaping with a `^`, or in case of the percent sign, doubling it. –  Sep 06 '19 at 09:32
  • It looks likes quotes can be nested. Is this always the case? – Martin Fehrs Sep 06 '19 at 09:37
  • there is no nesting. It's `"String1" ; "String2" ; "String3"` (inserted spaces for readability). – Stephan Sep 06 '19 at 13:57
  • @Stephen I'm talking about "%x:;=";"%" – Martin Fehrs Sep 06 '19 at 14:15
  • 1
    That might look like nesting, but in fact isn't. The parser first evaluates the variable, replacing `;` with `";"` (that's not a quoted `;`, but a quote plus a `;` plus another quote) and only then adds the quotes at the beginning and the end (that's technically still no quoting). After that, the `for` takes that construct and interprets it as quoted strings. If you want to know more, get yourself a big cup of coffee and some time to read [this](https://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts) – Stephan Sep 06 '19 at 17:53

0 Answers0