Question

I've searched a thousand of example and tried, but none of them actually works for me. My requirement is pretty straight forward, I have a file - config.txt, it has one of lines:

sqlServer=localhost

I'm trying to update this line to:

sqlServer=myMachine\sql2012

I looked examples online, some of them are just working with set variables, or some are not replacing but inserting. There are some examples are writing into a new file, but the new file has line number in front of each line. I don't find a useful instruction how to write batch scripts, and none of the update file batch scripts works for me.

It will be very helpful if you leave some comments.

Thanks in advance

Was it helpful?

Solution

EDITED - to adapt to comments

@echo off
    setlocal enableextensions disabledelayedexpansion

    set "config=.\config.txt"
    set "dbServer=localhost\sql2012"

    for /f "tokens=*" %%l in ('type "%config%"^&cd.^>"%config%"'
    ) do for /f "tokens=1 delims== " %%a in ("%%~l"
    ) do if /i "%%~a"=="sqlServer" (
        >>"%config%" echo(sqlServer=%dbServer%
    ) else (
        >>"%config%" echo(%%l
    )

    type "%config%"

    endlocal

Input file is read line by line (for /f %%l), then each line is split (for /f %%a) and if the first token in the line is "sqlserver" then the line is replaced, else the original line is sent to file.

The command used to retrieve the information in the first for loop includes an cd.>"%config%" that will remove the contents of the file, so the final resulting lines (that have been read in memory by the for command before removing them) are sent directly to the same file.

OTHER TIPS

You can do this:

FINDSTR /I /V /B "sqlServer=" config.txt > config.new
ECHO sqlServer=myMachine\sql2012 >> config.new
DEL config.txt
REN config.new config.txt

The FINDSTR will remove all lines that start with sqlServer= and create a new file called newfile.

The ECHO will add a line at the end with sqlServer=MyMachine\sql2012.

The last two lines delete your existing config.txt and replace it with the output of the first two lines.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top