简体   繁体   中英

batch script, find string in text file by line then replace whole line with another string

I want to write a batch file that find a given string in a text file by line then replace whole that line with another given string.

example : has file text.txt string_replace = abc string_replace_with = xyz if every line in text.txt that contains string_replace, so that line will be replaced with string_replace_with

Can any one help me ? Thanks alot

@echo off
SET InFile=test.txt
FOR /F "tokens=*" %%A IN ('FINDSTR "xyz" "%InFile%"') DO CALL :FindString "%%A"
pause
goto :eof
:FindString
SET String=%~1
SET String=%String:xyz=abc%
echo.%String%>getout.txt

Try these if it solve your problem. From your question what I understood is that you want to find and replace the word with desired word.

为自己准备一个Windows sed端口。

If you launch this SAR.BAT file like this it will replace abc with xyz

SAR "fileinput.txt" "fileoutput.txt" "abc" "xyz"

::Search and replace
@echo off
if "%~3"=="" (
echo.Search and replace
echo Syntax: 
echo %0 "filein.txt" "fileout.ext" "regex" "replace_text" [first]
echo.
echo. if [first] is present only the first occurrence is changed
goto :EOF
)
if "%~5"=="" (set global=true) else (set global=false)
set s=regex.replace(wscript.stdin.readall,"%~4")
 >_.vbs echo set regex=new regexp
>>_.vbs echo regex.global=%global%
>>_.vbs echo regEx.IgnoreCase=True            
>>_.vbs echo regex.pattern="%~3"
>>_.vbs echo wscript.stdOut.write %s%
cscript /nologo _.vbs <"%~1" >"%~2"
del _.vbs

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