Adis Sibic
Adis Sibic

Reputation: 33

Batch file for /f not escaping double quotes

So I'm using curl to get a download link from GitHub which is frequently changing. Using for /f I can split the string that curl returns by every front slash '/'

The variable I get looks like this

v0.30.2">redirected<

From this, I managed to extract the version using substring but it fails to work when the number of characters changes so I must manually edit the substring length.

To the issue Im trying to implement a for /f to extract the numbers from the variable above so I need use theese signs as delimiters v . " however whenever I try to use that double quotation as a delimiter I get nowhere. I read that using the escape char is the way to go but I'm not having any luck. Can anyone help?

Latest attempt at cracking this looked like this:

SetLocal EnableDelayedExpansion
set myStr=v0.30.2^"^>redirected^<
for /f tokens^=1-3 delims^=^.^"^v %%A in ("%myStr%") do (
   echo %%A
   echo %%B
   echo %%C
)
pause

The expected output should then be

0
30
2

Upvotes: 3

Views: 94

Answers (2)

jeb
jeb

Reputation: 82267

You missed one more caret, as the expresssion tokens=1-3 delims=.v" needs to be one block for the parser.
Normally this is archieved by simply quote the block like in FOR /F "tokens=1-3 delims=.v".
But in the special case where a double quote should be in the delimiter list, the outer quotes have to be omitted and instead the block has to be glued with carets.

for /f tokens^=1-3^ delims^...

And the expansion of myStr should be done by delayed expansion instead of percent expansion.

@echo off
SetLocal EnableDelayedExpansion
set ^"myStr=v0.30.2">redirected<"
for /f tokens^=1-3^ delims^=^.^"v %%A in ("!myStr!") do (
   echo %%A
   echo %%B
   echo %%C
)

Upvotes: 3

Compo
Compo

Reputation: 38604

I'm assuming that your %myStr% variable is actually part of a previous attempt to retrieve the string from a line. If that's the case then you could have further parsed that line to retrieve just the version number.

first like this:

Rem drop everything at the first doublequote
Set "myStr=%myStr:"="&:"%"

then this:

Rem keep everything from the first v
Set "myStr=%myStr:*v=%"

If you wanted to then just output the individual parts of it:

For %%A In (%myStr:.= %) Do Echo %%A

Upvotes: 2

Related Questions