Can't set a variable in a for loop

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Alain
Posts: 2
Joined: 07 Aug 2017 02:44

Can't set a variable in a for loop

#1 Post by Alain » 07 Aug 2017 03:10

Hello,

I try to write a DOS batch but I can't get the expected result.
I've got a file with a header and I want to get the value of the first column of the second record. Then I want to split the value in two in order to get the year (which I concatenate with FY ==> FY17) and the month (which I concatenate with M ==> M04 for example).

Code: Select all

FOR /f "tokens=1,* delims=:" %%i in ('findstr /n /r . %fictodo%') do if %%i == 2 echo %%j > %fic1%

FOR /f "tokens=1,2* delims=;" %%a in ('type %fic1%') do (
    set anneemois=%%a
    echo anneemois %anneemois%
    echo %%a
    call set annee=FY%anneemois:~2,2%
    call set mois=M%anneemois:~4,2%
    echo annee= %annee%
    echo mois= %mois%
)



%%a is well set with the expected value 201704. Fine
But anneemois, annee or mois remain empty.

fictodo is the file in. I add it in attachment.

Could you please help me with this issue?

Thanks.

SIMMS7400
Posts: 546
Joined: 07 Jan 2016 07:47

Re: Can't set a variable in a for loop

#2 Post by SIMMS7400 » 07 Aug 2017 04:32

You need to delay expansion:

Code: Select all

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

FOR /f "tokens=1,* delims=:" %%i in ('findstr /n /r . %fictodo%') do if %%i == 2 echo %%j > %fic1%

FOR /f "tokens=1,2* delims=;" %%a in ('type %fic1%') do (
    set anneemois=%%a
    echo anneemois !anneemois!
    echo %%a
    call set annee=FY!anneemois:~2,2!
    call set mois=M!anneemois:~4,2!
    echo annee= !annee!
    echo mois= !mois!
)
pause>nul

aGerman
Expert
Posts: 4678
Joined: 22 Jan 2010 18:01
Location: Germany

Re: Can't set a variable in a for loop

#3 Post by aGerman » 07 Aug 2017 05:02

Just two additional links that explain the behavior ...
viewtopic.php?t=6866
viewtopic.php?f=3&t=8013&p=53253#p53253

Steffen

Alain
Posts: 2
Joined: 07 Aug 2017 02:44

Re: Can't set a variable in a for loop

#4 Post by Alain » 07 Aug 2017 06:53

Thank you so much for both of you.
Brilliant.

Alain

Post Reply