Windows – Find and replace text via batch file

batcheditingwindows

I have seen this question asked but never with a suitable answer for what I need

I work doing remote tech support on computer systems and one of the things I frequently need to do is open ini files and replace certain lines with a new one

as an example we will say.

program.ini

program status = client

Well I would need to change that to server so it reads

program status = server

While yes I can open it in notepad I want to be able to do this via command line in a batch file as I already have a batch tool I have created for everything else I do.

Now, note that not every computer supports powershell scripts so this has to be just in the one batch file. I can not download any additional software as these are not my systems I am connecting to.

Anyone know how this would be done purely via batch as I am at a loss.
Not looking to open an editor via command line, just a straight up run it and that line is changed in the ini file.

Thanks for any input
-Terra

Best Answer

This batch file includes some diagnostic information, too. The setlocal line is REQUIRED in order to properly play with variables in a loop.

The most significant side-effects of using this method are that blank lines are removed (they're ignored by FOR) and that your tests (in the "write out the new value" section) are very specific: spaces and case matter. You can perform case insensitive matching with /i, but since you're including the spaces in your question I suspect you prefer to include them. You'll need to include multiple lines as done in that section to replicate each possible comparison.

@ECHO OFF
setlocal enableDelayedExpansion

FOR /F "tokens=1,* delims==" %%i IN (test.ini) DO (
    SET sdone=0
    SET "sname=%%i"
    SET "svalue=%%j"
    ECHO.Name:  !sname!
    ECHO.Value: !svalue!

    :: write out headers
    IF "!sdone!"=="0" IF "!sname:~0,1!"=="[" SET sdone=1&&ECHO.Type:  Header&&ECHO.!sname!>>new.ini

    :: write out the new value if it's client
    IF "!sdone!"=="0" IF "!sname!"=="program status" IF "!svalue!"=="client" SET sdone=1&&ECHO.Type:  Rewrite&&ECHO.!sname!=server>>new.ini
    IF "!sdone!"=="0" IF "!sname!"=="program status " IF "!svalue!"==" client" SET sdone=1&&ECHO.Type:  Rewrite&&ECHO.!sname!=server>>new.ini

    :: write out anything else
    IF "!sdone!"=="0" SET sdone=1&&ECHO.Type:  Content&&ECHO.!sname!=!svalue!>>new.ini

    :: a little padding to read the debug info
    ECHO.
)

At the end you'll want to add something to overwrite the original file, something like:

copy /y new.ini test.ini
Related Question