1

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.

1 Answer 1

1
@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 %

Sign up to request clarification or add additional context in comments.

2 Comments

Holy crap, it worked. Can you explain why is this? Sound really counter-intuitive to me.
@LordZozzy - here's some explanation and examples - ss64.com/nt/delayedexpansion.html .With %..% the value is expanded\replaced during the reading of the script and everything in brackets is taken for one-line expression.With delayed expansion and !..! the expression is replaces\expanded during execution and if there are any changes in variable value they are taken into account.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.