如何使用批处理脚本替换文件中的两行文本

时间:2018-10-01 11:28:44

标签: batch-file

我需要替换文本文件中的两个字符串行。 我写了一个替换一个字符串的脚本:

@echo off
setlocal enabledelayedexpansion

rem file name
Set infile=file.txt

rem what to find
Set find=123

rem value to replace
Set replace=321

@echo off
setlocal enabledelayedexpansion
set COUNT=0
for /F "tokens=* delims=," %%n in (!infile!) do (
set LINE=%%n
set TMPR=!LINE:%find%=%replace%!
Echo !TMPR!>>tmp.txt
)
move tmp.txt %infile%
pause

如何修改它以一次替换2行?我的意思是“查找”为“替换”,“查找2”为“替换2”?

2 个答案:

答案 0 :(得分:1)

在您的set TMPR=...之后,添加set TMPR=!TMPR:%find2%=%replace2%!

@echo off
setlocal enabledelayedexpansion
del tmp.txt
rem file name
Set infile=file.txt

rem what to find
Set find=abc
set find2=def

rem value to replace
Set replace=123
set replace2=456

for /F "tokens=* delims=," %%n in (!infile!) do (
set LINE=%%n
set TMPR=!LINE:%find%=%replace%!
set TMPR=!TMPR:%find2%=%replace2%!
Echo !TMPR!>>tmp.txt
)
type tmp.txt

file.txt:

aaa
abc
bbb
def
ccc
xxxabcyyy
uuudefvvv
nnnabcdefmmm

输出:

aaa
123
bbb
456
ccc
xxx123yyy
uuu456vvv
nnn123456mmm

答案 1 :(得分:-1)

是否没有其他方法可以将2值传递给搜索属性字符串并替换该值的函数? 像:

代码:

CALL :modify prop.first.name , myName
CALL :modify prop.last.name , myLastName
:modify

set "source=srcFile.txt"
set "target=tmpFile.txt"

set property=%~1
set value=%~2

setlocal enableDelayedExpansion
(
for /F "tokens=1* delims==" %%a in ('findstr /B "^" %source%') do (
  set line=%%b
  if defined line echo !line:%property%=%property%=%value%!
)
) > %target%
 endlocal

源文件如下:

prop.first.name =名字

prop.last.name =姓氏

prop.pssw.word =密码

prop.url.link = alink

需要在输入的=“ =”等号后替换值

想法是使用不同的参数调用通用函数4次