Sourav Ghosh
Sourav Ghosh

Reputation: 2024

What is wrong with the following batch code?

@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
)

In the above batch file It does not echo the value of name and email

But if I use,

@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

It shows desired output with name and email.

Can you please explain why this is happening?

Thank you.

Upvotes: 0

Views: 39

Answers (1)

Jason Faulkner
Jason Faulkner

Reputation: 6558

In the first block, you are setting the name and email variables within the FOR block. If you then want to access this value then you must have delayed expansion enabled. Without delayed expansion then the contents of the FOR loop are only parsed when the loop starts - at which point name and email do not have a value.

This edit should make the block work:

@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

The second block works because each iteration of the loop calls the subroutine which causes the execution to parse on each pass.

Upvotes: 2

Related Questions