Edit text file using batch file
batch-file, line, replace
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.
Problem
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