在 FOR 循环中为 windows cmd 中的 sed 转义正则表达式字符串
Escape regex string for sed in windows cmd in FOR loop
我有一个 sed
命令,当它自己发出时,它会准确地抓取它应该抓取的部分:
sed -r -n 's/^.+new_ldap_user.+authenticity_token.+value="([^"]+).+//p' response.html
到目前为止一切顺利。现在,当我尝试将此片段放入 FOR
循环中以将 sed
的结果存储在变量中时,我不知道如何正确转义几个引号/括号。
我尝试过的:
FOR /F %i IN ('sed -r -n ^'s/^.+new_ldap_user.+authenticity_token.+value="([^"]+).+//p^' response.html') DO set AUTH=%i
.+//p' was unexpected at this time.
所以在我看来,我也必须转义右括号:
FOR /F %i IN ('sed -r -n ^'s/^.+new_ldap_user.+authenticity_token.+value="([^"]+^).+//p^' response.html') DO set AUTH=%i
此代码至少不会导致错误,但也不会导致 AUTH
被正确设置。
我也尝试将 regex
中的所有插入符 ^
加倍,但无济于事。
我需要如何正确转义我的 sed
子命令才能将其结果存储在 AUTH
中?
有点棘手,因为插入符号在批处理文件本身中使用,后来在子 cmd 实例中再次使用。
将命令存储到变量中并延迟扩展到子实例中更容易,然后插入符号只需转义一次,括号不需要任何转义。
@echo off
set "cmd=sed -r -n 's/^^.+new_ldap_user.+authenticity_token.+value="([^^"]+).+//p' response.html"
FOR /F "delims=" %%i in ('"%%cmd%%"') DO (
echo ## %%i
)
命令行上下文
这有点棘手,因为 %%cmd%%
的晚期百分比扩展在这里不起作用。
但是你可以用
来模拟
FOR /F "delims=" %i in ('^"%^cmd%^"') DO echo %i
我有一个 sed
命令,当它自己发出时,它会准确地抓取它应该抓取的部分:
sed -r -n 's/^.+new_ldap_user.+authenticity_token.+value="([^"]+).+//p' response.html
到目前为止一切顺利。现在,当我尝试将此片段放入 FOR
循环中以将 sed
的结果存储在变量中时,我不知道如何正确转义几个引号/括号。
我尝试过的:
FOR /F %i IN ('sed -r -n ^'s/^.+new_ldap_user.+authenticity_token.+value="([^"]+).+//p^' response.html') DO set AUTH=%i
.+//p' was unexpected at this time.
所以在我看来,我也必须转义右括号:
FOR /F %i IN ('sed -r -n ^'s/^.+new_ldap_user.+authenticity_token.+value="([^"]+^).+//p^' response.html') DO set AUTH=%i
此代码至少不会导致错误,但也不会导致 AUTH
被正确设置。
我也尝试将 regex
中的所有插入符 ^
加倍,但无济于事。
我需要如何正确转义我的 sed
子命令才能将其结果存储在 AUTH
中?
有点棘手,因为插入符号在批处理文件本身中使用,后来在子 cmd 实例中再次使用。
将命令存储到变量中并延迟扩展到子实例中更容易,然后插入符号只需转义一次,括号不需要任何转义。
@echo off
set "cmd=sed -r -n 's/^^.+new_ldap_user.+authenticity_token.+value="([^^"]+).+//p' response.html"
FOR /F "delims=" %%i in ('"%%cmd%%"') DO (
echo ## %%i
)
命令行上下文
这有点棘手,因为 %%cmd%%
的晚期百分比扩展在这里不起作用。
但是你可以用
来模拟FOR /F "delims=" %i in ('^"%^cmd%^"') DO echo %i