@echo off
for /L %%g in (1 1 2) do (
FOR /F "delims=" %%l IN ('findstr /i "<h1>" output.txt')DO set name=%%l
FOR /F "tokens=3 delims=><" %%l IN ("%name%") DO echo %%l
FOR /F "delims=" %%m IN ('findstr /i /r ".*@.*\..*</label>" output.txt')DO set email=%%m
FOR /F "tokens=3 delims=><" %%m IN ("%email%") DO echo %%m
)
在上面的批处理文件中它不会回显名称和电子邮件的值
但如果我使用,
@echo off
for /L %%g in (1 1 2) do (
call :sub
)
:sub
FOR /F "delims=" %%l IN ('findstr /i "<h1>" output.txt') DO set name=%%l
FOR /F "tokens=3 delims=><" %%l IN ("%name%") DO echo %%l
FOR /F "delims=" %%m IN ('findstr /i /r ".*@.*\..*</label>" output.txt')DO set email=%%m
FOR /F "tokens=3 delims=><" %%m IN ("%email%") DO echo %%m
它显示了带名称和电子邮件的所需输出。
你能解释为什么会这样吗?
谢谢。
答案 0 :(得分:2)
在第一个区块中,您要在 name
区块内设置email
和FOR
变量。如果您想要访问此值,则必须启用延迟扩展。如果没有延迟扩展,那么FOR
循环的内容仅在循环开始时被解析 - 此时name
和email
没有值。
此编辑应该使块工作:
@echo off
REM Turn on the delayed expansion option.
SETLOCAL EnableDelayedExpansion
REM Note how "name" and "email" is wrapped in exclamation marks below.
REM This is delayed expansion notation.
for /L %%g in (1 1 2) do (
FOR /F "delims=" %%l IN ('findstr /i "<h1>" output.txt')DO set name=%%l
FOR /F "tokens=3 delims=><" %%l IN ("!name!") DO echo %%l
FOR /F "delims=" %%m IN ('findstr /i /r ".*@.*\..*</label>" output.txt')DO set email=%%m
FOR /F "tokens=3 delims=><" %%m IN ("!email!") DO echo %%m
)
ENDLOCAL
第二个块有效,因为循环的每次迭代都会调用子例程,这会导致执行在每次传递时解析。