3

I'm very new to batch scripting, but in my last question I was trying to extract a link from a line of text, specifically:

83:                   href="https://beepbeep.maxresdefault.rar"><img

What I want out of it is this:

https://beepbeep.maxresdefault.rar

Someone suggested using for /f to separate the string, and I'd like to separate it every " mark, taking only the second token, as what I want is trapped between the two "".

Here is what I've got:

for /f "delims=^" tokens=^2" %%G in (output2.txt) do @echo %%G %%H >> output3.txt

The batch crashes at this point, I'm guessing it's the wrong syntax, but I'm not sure where the issue is, maybe in the " part?

theboy
  • 353
  • 2
  • 10

2 Answers2

3

See how we delimit on double quotes, without surrounding quotes. We have already assigned the variable between the quotes to %%a but if we did not, then to remove the double quotes from the string we expand the variable %%a to %%~a (see for /? on variable expansion):

@for /f delims^=^"^ tokens^=2 %%a in (output2.txt) do @echo %%~a
Gerhard
  • 22,678
  • 7
  • 27
  • 43
2

Neat problem.

I'd do it this way:

SETLOCAL ENABLEDELAYEDEXPANSION

for /F "tokens=2 delims=^>=" %%i in (output2.txt) do (
  set x=%%i
  set x=!x:"=!
  echo !x! >> output3.txt
)

Notes:

  • Instead of tokenising on the quote, I've tokenised on = (before) and > (after). Because, as you already know, quotes are hard
  • I always do the delims last. Otherwise it might think the space between delims and tokens is a delimeter.
  • Then it uses the SET syntax that allows you to substitute one character for another to replace all occurances of the double quote with nothing.
  • The SETLOCAL ENABLEDELAYEDEXPANSION is necessary because otherwise, each evaluation of the %x% in the loop uses the original value of %x% which is probably wrong. I always have this as the second line in my batch file.

Judging by how much you've already got, I'm guessing you've seen it, but if you haven't, I've found ss64.com to be the best resource.
https://ss64.com/nt/syntax-dequote.html

GregHNZ
  • 7,946
  • 1
  • 28
  • 30
  • 2
    You have posted a link to `dequote` yet you never used it? `:)` Rather expand on the metavariable to remove double quotes `set "x=%%~i"` then remove the substitution line `set x=!x:"=!`... That being said, if you do that, then `delayedexpansion` is not needed at all and the entire script would simply be `for /F "tokens=2 delims=^>=" %%i in (output2.txt) do echo %%~i >>output.txt` – Gerhard Nov 15 '19 at 06:02