Home > Back-end >  BATCH set varibale in if statement when value equals Y
BATCH set varibale in if statement when value equals Y

Time:09-20

I have searched the forum and see this question asked often but I can not seem to get it to work for me. I am trying to set a variable when a value equals Y. Here is what I think should work but mer2 is not being set.

setlocal ENABLEDELAYEDEXPANSION
for /F "tokens=*" %%A in (C:\SOMEFILE.txt) do (
set var=%%A
set mer1=!var:~0,1!
if "!mer1!"=="Y" (
set mer2=!1.5!
)
set "y=!mer1!,!mer2!"
echo !y!>>C:\SOMENEWFILE.csv
)

MY input file looks like this

Y
Y
N
N
Y

My expected output is this:

Y,1.5
Y,1.5
N,
N,
Y,1.5

What am I doing wrong?

CodePudding user response:

You have two issues: set mer2=!1.5! should probably be set mer2=1.5 and you never undefine it, so once you met a Y, 1.5 will be added to each following line.
I'd do it a bit different (using just one variable in the loop is enough):

@echo off
setlocal ENABLEDELAYEDEXPANSION
(for /F "tokens=*" %%A in (SOMEFILE.txt) do (
set var=%%A
set var=!var:~0,1!
if "!var!"=="Y" (echo Y,1.5) else echo !var!,
))>C:\SOMENEWFILE.csv

Redirecting the whole loop in one go is a lot faster than writing each and every single line (you won't notice it on a small file, but on a big file, it can sum up to a factor of 100 and more. (I once had a factor of >1000 with a really big file)

  • Related