LordZozzy
LordZozzy

Reputation: 13

Batch - setting a variable via IF statement in FOR loop "stuck"

I'm working on this lil' script that reads columns from the input file:

@echo off
setlocal enabledelayedexpansion
FOR /F "tokens=2,3,4,5,7,8,9,12,14" %%a IN ('type %1') do (
    set event="NULLA"
    echo %event% - %%h
    if "%%h"=="i" ( set event=FELTOLTES )
    echo %event% - %%h
    if "%%h"=="o" ( set event=LETOLTES )
    echo %event% - %%h
    if "%%h"=="d" ( set event=TORLES )
    echo %event% - %%h  
    echo ---------------------
}

However, if I run it, the %event% variable in ALL steps (even the first one, before the if "%%h"=="i"), and all rows of the input file is "TORLES", which is defined in the last IF statement:

TORLES - i
TORLES - i
TORLES - d
TORLES - i  
TORLES - d
TORLES - d
TORLES - o
TORLES - d

Am I doing something wrong here? Tried adding-removing quotation marks around the IF statements, but yielded no success.

Upvotes: 1

Views: 341

Answers (1)

npocmaka
npocmaka

Reputation: 57252

@echo off
setlocal enabledelayedexpansion
FOR /F "tokens=2,3,4,5,7,8,9,12,14" %%a IN ('type %1') do (
    set event="NULLA"
    echo !event! - %%h
    if "%%h"=="i" ( set event=FELTOLTES )
    echo !event! - %%h
    if "%%h"=="o" ( set event=LETOLTES )
    echo !event! - %%h
    if "%%h"=="d" ( set event=TORLES )
    echo !event! - %%h

    echo ---------------------
)

When you use delayed expansion and try to set/access variables in brackets context you need to access it with ! instead of %

Upvotes: 1

Related Questions