1

I am trying to read from file and assign the read value to variable and perform a task. However I see that I succeed in reading value correctly from file, however the assignment part doesn't work fine. Also I am struggling to clear the set value post assignment. I have looked at SO-link1 for reading and assigning value and SO-link2 for clearing the assigned value

Based on the link provided I added below line but it doesnt solve the problem

setlocal enabledelayedexpansion

To add more my key file has numbers like below

12456

23890

45389

12690

Code Snippet:

for /F "delims=" %%x in (key.txt) do 
( 
echo value read from file -- %%x            **Shows correct value**
set "SERIAL=%%x"
echo number which got assigned -- %SERIAL%  **Shows incorrect value**
set "SERIAL="                               ** Doesnt clear the set value**
)
oneday
  • 629
  • 1
  • 9
  • 32
  • 1
    Possible duplicate of [Windows Batch Variables Won't Set](https://stackoverflow.com/questions/9681863/windows-batch-variables-wont-set) (or unset, in your second problem's case). – SomethingDark Jan 18 '18 at 05:51
  • @SomethingDark - I tried out the suggestion from the link but it doesn't help – oneday Jan 18 '18 at 05:58
  • 1
    That's because you did it wrong. I don't know what you ended up trying, but I can say with 100% certainty that you did not enable delayed expansion and then use `!SERIAL!` like you were supposed to. – SomethingDark Jan 18 '18 at 06:22
  • Yes usage of !SERIAL! was missing along with delayed expansion. – oneday Jan 18 '18 at 06:26

1 Answers1

2

Try with enabledelayedexpansion

@echo off
setlocal enabledelayedexpansion
for /F "delims=" %%x in (key.txt) do ( 
  echo value read from file -- %%x
  set "SERIAL=%%x"
  echo number which got assigned -- !SERIAL!
  set "SERIAL=" 
)

For more on the subject, you can perform setlocal /? from cmd.exe

Gerhard
  • 22,678
  • 7
  • 27
  • 43
  • @OP: Note the position of the `(` after the `do` - it **must** be on the same physical line as the `do`. You need to invoke delayedexpansion [hundreds of SO articles about that - use the search feature] in order to display or use the run-time value of any string variable that's changed within a parenthesised series of instructions (aka "code block"). – Magoo Jan 18 '18 at 06:12
  • @Magoo - while editing for code, location of ( got shifted. Thanks for the pointer however. – oneday Jan 18 '18 at 06:20