简体   繁体   中英

batch: replace a line in a text file


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)...

Lines containing ! are corrupted because delayed expansion occurs after FOR variable ( %%A ) expansion. That could be solved by starting out with delayed expansion disabled. Within the loop you save the value of %%A in a variable, and then toggle delayed expansion on, process the line, and then toggle it back off.

You do not need to expand the variable within a SET /A computation.

You can do everything in one step by adding an IF statement within your loop.

In fact, you don't even need SET /A or FINDSTR at all. Your IF statement can test if the line matches your search string. You don't really need delayed expansion for your problem.

It is more efficient to enclose the entire loop within parens and redirect to your output file just once.

@echo off
setlocal disableDelayedExpansion

:Variables
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 ."

:Replace
>"%OutputFile%" (
  for /f "usebackq delims=" %%A in ("%InputFile%") do (
    if "%%A" equ "%_strFind%" (echo %_strInsert%) else (echo %%A)
  )
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM