batch: replace a line in a text file
Posted
by
sasamimasas
on Stack Overflow
See other posts from Stack Overflow
or by sasamimasas
Published on 2012-11-04T14:56:35Z
Indexed on
2012/11/04
17:00 UTC
Read the original article
Hit count: 184
I'm trying to replace this line:
# forward-socks5 / 127.0.0.1:9050 .
with this one:
forward-socks5 / 127.0.0.1:9050 .
this line belongs to a config file that has to be enabled (UN-commented) by deleting the # sign from the beginning and I could not thought of a better way other than replacing the line with another without the # sign.
any other thoughts or ways would be very useful.
btw, the spaces before the text are there also.
I have pasted the text as it was in the original file.
thanks in advance
EDIT:
I have somehow managed to do the line addition and removing using two peaces of code that I've found.
my only problem is that the following code removes every bit of exclamation in the output file!
@echo off
:Variables
SETLOCAL ENABLEDELAYEDEXPANSION
set InputFile=config.txt
set OutputFile=config-new.txt
set _strFind=# forward-socks5 / 127.0.0.1:9050 .
set _strInsert= forward-socks5 / 127.0.0.1:9050 .
set i=0
:Replace
for /f "usebackq tokens=1 delims=[]" %%A in (`find /n "%_strFind%" "%InputFile%"`) do (set _strNum=%%A)
for /f "usebackq delims=" %%A in ("%InputFile%") do (
set /a i = !i! + 1
echo %%A>>"%OutputFile%"
if [!i!] == [%_strNum%] (echo %_strInsert%>>"%OutputFile%")
)
type %OutputFile% | findstr /i /v /c:"%_strFind%">config-new2.txt
I was wondering if there is any way to do both the find/delete/add line in one step (not two steps as mine)...
© Stack Overflow or respective owner