简体   繁体   中英

String replace with variable in batch

I would like to replace some part of a string in batch with an other 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 basics CSV files. In the fonction addId, the line "call set result=%string:!id!=;HELLO;%" doesn't work. The string is still the same. How can i fix this ?

Try this instead:

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

Alternatively, test this:

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

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%

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM