Home > OS >  Changing FOR Loop Variable Value in another file
Changing FOR Loop Variable Value in another file

Time:06-20

Im trying to change the %%A value after using Findstr to locate the first matched string. %%A is located in a separate file and after looking over multiple other posts, i cant figure out a solution. I am relatively new to batch scripting but im an extremely fast learner when i can find tutorials or explanations that help me connect two things. Code shown below.

for /f "delims=" %%A in ('findstr "nila" Players\%name1%.bat') do ( 
     Echo %%A
     Set %%A=%%A:nila=Bronze Dagger%
     Echo %%A
     pause
     goto Shop1
)

CodePudding user response:

setlocal enabledelayedexpansion
for /f "delims=" %%A in ('findstr "nila" Players\%name1%.bat') do ( 
     Echo %%A
 set "string=%%A"
 Set "string=!string:nila=Bronze Dagger!"
     Echo !string!
     pause
     goto Shop1
)

Such operations cannot be performed directly on a metavariable such as %%A but need to be manipulated through an ordinary user-variable.

Note that since the value of string is changing within a code block (parenthesised sequence of lines) then you need to use delayedexpansion and !var! to access the changed value.

see Stephan's DELAYEDEXPANSION link

Use set "var=value" for setting string values - this avoids problems caused by trailing spaces. Don't assign a terminal backslash, Space or " - build pathnames from the elements - counterintuitively, it is likely to make the process easier

Tip for game-generation:

If you reserve a character as a prefix for variables-you-want-to-save (eg all variables I want to save/reload start with #) then all you need to save a game is

set #>"mygamefile.txt"

and all you need to reload a game is

for /f "usebackqdelims=" %%a in ("mygamefile.txt") do set "%%a"

To zap all # variables (useful before reloading a game) use

for /f "delims==" %%a in ('set # 2^>nul') do set "%%a="

CodePudding user response:

Resolved the issue by splitting data file into separate files and making a load function to load the variable and then change it before saving again.

  • Related