在文本文件中查找和replacestring

我必须使用Windows命令/批处理脚本来replace文本文件( InputFile.txt )中的string。 我发现下面的脚本( replace.cmd ),但它不给我准确的结果。

InputFile.txt

 1111 aaaa 2222 bbbb $cc = 3333 

我正在使用的批处理脚本( replace.cmd )将$cc = 3333replace为cc = 4444

 @echo OFF setlocal enabledelayedexpansion set "search=$cc = 3333" set "replace=cc = 4444" set "textfile=InputFile.txt" set "newfile=OutputFile.txt" (for /f "delims=" %%i in (%textfile%) do ( set "line=%%i" setlocal enabledelayedexpansion set "line=!line:%search%=%replace%!" echo(!line! endlocal ))>"%newfile%" 

运行代码后得到的输出是:

 1111 aaaa 2222 bbbb 3333=cc = 4444= 3333 

它应该是这样的:

 1111 aaaa 2222 bbbb cc = 4444 

如果你想要一个像这样的VBScript一个小技巧:

 @echo off set "Data=some data .... $cc = 3333" echo The data before replacing is "%Data%" & pause set "String1=$cc = 3333" set "String2=cc = 4444" Call :ReplaceString "%Data%" "%String1%" "%String2%" echo The data after replacing is "%Data%" & pause & exit ::************************************************************************************* :ReplaceString <Data> <String1> <String2> ( echo Wscript.echo Replace("%~1","%~2","%~3"^) )>"%tmp%\%~n0.vbs" for /f "delims=" %%a in ('Cscript /nologo "%tmp%\%~n0.vbs"') do ( set "Data=%%a" ) If Exist "%tmp%\%~n0.vbs" Del "%tmp%\%~n0.vbs" exit /b ::************************************************************************************* 

编辑:在15/09/2016 @ 19:30

 @echo off Set "InputFile=%~dp0InputFile.txt" Set "OutputFile=%~dp0OutputFile.txt" set "String1=$cc = 3333" set "String2=cc = 4444" if exist "%OutputFile%" Del "%OutputFile%" Setlocal EnableDelayedExpansion for /f "delims=" %%i in ('Type "%InputFile%"') do ( If /I "%%i" == "%String1%" ( Call :ReplaceString "%%i" "%String1%" "%String2%" echo !Data! ) else ( echo %%i ) )>> "%OutputFile%" start "" "%OutputFile%" & exit ::************************************************************************************* :ReplaceString <Data> <String1> <String2> ( echo Wscript.echo Replace("%~1","%~2","%~3"^) )>"%tmp%\%~n0.vbs" for /f "delims=" %%a in ('Cscript /nologo "%tmp%\%~n0.vbs"') do ( set "Data=%%a" ) If Exist "%tmp%\%~n0.vbs" Del "%tmp%\%~n0.vbs" exit /b ::************************************************************************************* 

我们需要一个专家在这里! 他/她知道如何做到这一点。

用一个包含=符号的字符串代替是很棘手的。 据我所知,你必须分成两部分,并测试两个术语,或者,如果搜索字符串是固定的,请尝试

 @echo off set "search=$cc = 3333" set "replace=cc = 4444" set "textfile=InputFile.txt" set "newfile=OutputFile.txt" >"%newfile%" ( for /f "delims=" %%i in (%textfile%) do ( if "%%i" equ "%search%" ( echo(%replace% ) else ( echo(%%i ) ) ) exit/B 

只要改变你的循环:

 @echo off set "search=$cc = 3333" set "replace=cc = 4444" set "textfile=InputFile.txt" set "newfile=OutputFile.txt" >"%newfile%" (for /f "delims=" %%i in (%textfile%) do ( If /I "%%i" Equ "%search%" (Echo=%replace%) Else (Echo=%%i))) exit/B