String replace inside a for loop in bat script

11,265

The problem is the expansion of the variable. If the variable is modified inside the for block of code, to access its value inside the same block you need delayed expansion.

But you can not do something like !lineString:!to_replace!=! as the parser will interpret the opening ! in to_replace as the termination og lineString.

So, you have two options.

The easiest one needs that value to be replaced to be known before the for command starts. Just define to_replace before the for command. When the parser reaches the for command the variable has the correct value and is properly expanded.

But if for any reason you have to define the value of the variable inside the for command, you will need to change your code as

for /f "tokens=* delims= " %%a in ( .... ) do (
    set "lineString=%%a"

    set "to_replace= .... "
    for %%b in ("!to_replace!") do set "str2=!lineString:%%~b=!"

    echo !str2!
)

This stores the value in the variable into a new for replaceable parameter that is used in the replace expression

Share:
11,265
Jeff Lee
Author by

Jeff Lee

Updated on September 18, 2022

Comments

  • Jeff Lee
    Jeff Lee almost 2 years

    The replace is go well in this script. I am trying to make it dynamic.

    SETLOCAL enabledelayedexpansion
    for /f "tokens=* delims= " %%a in (C:\workspace\iwms_kw_patch_script\BuildPatchScript\140903111828_batch_file.txt) do (
        set lineString=%%a
    
        set str2=!lineString:C:\iwms_builder_working_directory\tmp\IWMS_KW_01_CBI_2014-003\=!
        echo !str2!
    
        echo IF NOT %ERRORLEVEL%==0 GOTO ERROR_HANDLER2 >> %output_file%
    )
    endlocal
    

    And this one is not working..

    SETLOCAL enabledelayedexpansion
    for /f "tokens=* delims= " %%a in (C:\workspace\iwms_kw_patch_script\BuildPatchScript\140903111828_batch_file.txt) do (
        set to_replace=C:\iwms_builder_working_directory\tmp\IWMS_KW_01_CBI_2014-003\
        set lineString=%%a
        set str2=!lineString:%to_replace%=!
        echo !str2!
    
        echo IF NOT %ERRORLEVEL%==0 GOTO ERROR_HANDLER2 >> %output_file%
    )
    endlocal
    

    Can I do a string replace with variable inside a for loop? Thank :D