How to search and replace a string that have an equal-to sign “=” inside

前端 未结 2 1203
梦毁少年i
梦毁少年i 2020-11-27 23:47

i have to search a string from a txt like Pippo.K=5 and replace it with Pippo.K=1. I need to search the entire string. What i did is:

set \"search=Pippo.K=5\         


        
2条回答
  •  爱一瞬间的悲伤
    2020-11-28 00:21

    Batch variable substring substitution does have limitations. Dealing with literal equal signs is one of them.

    powershell "(gc \"%textFile%\") -replace '%search%','%replace%'"
    

    would work. That PowerShell one-liner is a simple alternative to your for /f loop without that limitation.


    If you prefer a for /F loop, if your text file is an ini-style file, try this:

    @echo off & setlocal
    
    set "searchItem=Pippo.K"
    set "searchVal=5"
    set "newVal=1"
    set "textFile=test.txt"
    
    >"outfile.txt" (
        for /f "eol=; usebackq tokens=1* delims==" %%I in ("%textFile%") do (
            if /I "%%~I"=="%searchItem%" (
                if "%%~J"=="%searchVal%" (
                    echo %%I=%newVal%
                ) else echo %%I=%%J
            ) else (
                if not "%%~J"=="" (echo %%I=%%J) else echo %%I
            )
        )
    )
    move /y "outfile.txt" "%textFile%"
    

    Be advised that if any of the items in your file has a blank value (e.g. valuename=), the equal sign will be stripped unless you add some additional logic.

    You might also consider using ini.bat from this answer.

提交回复
热议问题