Escape regex string for sed in windows cmd in FOR loop

Viewed 127

I have a sed command, which, when issued on its own, grabs exactly the piece which it shoulds:

sed -r -n 's/^.+new_ldap_user.+authenticity_token.+value="([^"]+).+/\1/p' response.html

So far so good. Now when I try to put this piece into a FOR loop to store the result from sed in a variable I have no clue how to escape the several quotes / brackets properly.

What I have tried:

FOR /F %i IN ('sed -r -n ^'s/^.+new_ldap_user.+authenticity_token.+value="([^"]+).+/\1/p^' response.html') DO set AUTH=%i

.+/\1/p' was unexpected at this time.

So it seems to me that I also have to escape the closing bracket:

FOR /F %i IN ('sed -r -n ^'s/^.+new_ldap_user.+authenticity_token.+value="([^"]+^).+/\1/p^' response.html') DO set AUTH=%i

This code does at least not result in an error, but it does not result in AUTH to be set properly either.

I tried to double all carets ^ within the regex as well, but to no avail.

How do I need to properly escape my sed subcommand to be able to store it results in AUTH?

1 Answers

A bit tricky, because the caret is used in the batch file itself, and later it's used again in the sub-cmd instance.

It's easier to store the command into a variable and delay the expansion into the child instance, then the caret has to be escaped only once and the parenthesis don't need any escapes.

@echo off

set "cmd=sed -r -n 's/^^.+new_ldap_user.+authenticity_token.+value="([^^"]+).+/\1/p' response.html"

FOR /F "delims=" %%i in ('"%%cmd%%"') DO (
    echo ## %%i
)

command line context

This is a bit more tricky, because the late percent expansion of %%cmd%% doesn't work here.

But you can simulate it with

FOR /F "delims=" %i in ('^"%^cmd%^"') DO echo %i
Related