Vincent ROSSIGNOL
Vincent ROSSIGNOL

Reputation: 559

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?

Upvotes: 1

Views: 10120

Answers (2)

Roman
Roman

Reputation: 857

I just had the problem that it seems to be impossible to directly use the command line arguments (like %1) in a batch script.
I had to use an intermediate variable like this:

set oldstring=%1
set newstring=%oldstring:oldpart=newpart%

Upvotes: 1

sambul35
sambul35

Reputation: 1098

Try this instead:

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

Alternatively, test this:

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

Upvotes: 3

Related Questions