Search code examples
windowsbatch-filecmd

String replace with variable in batch


I would like to replace some part of a string in batch with another string. But I don't know what this string will be.

So I would like to use a variable for this:

for /r %%i in (\file\tmp\*) do (
    call :createJob %%i 
)
goto :eof

:createJob
    SETLOCAL
    set filename=%1
    for /F "delims=" %%i in (%filename%) do (
        set "line=%%i"
    )
    call :addId "%line%"
    ENDLOCAL
goto :eof

:addId
    @setlocal enableextensions enabledelayedexpansion
    set string=%~1
    set /A "i=0"
    echo %string%
    for %%a in (%string%) do (
        if !i! EQU 1 (
            set id=;%%a;
            call set result=%string:!id!=;HELLO;%
        )
        echo %%a
        set /A "i+=1"
    )
    echo %result%
    ENDLOCAL
goto :eof   

:eof

I'm reading basic CSV files. In the function addId, the line "call set result=%string:!id!=;HELLO;%" doesn't work. The string is still the same. How can I fix this?


Solution

  • Try this instead:

    call set result=%%string:!id!=;HELLO;%%
    

    Alternatively, test this:

    set result=!string:;%%a;=;HELLO;!