引起问题的报价在哪里发挥作用?
有没有办法用另一个文件的文本内容替换文本?你的意思是用另一个文件中的片段替换某些片段吗?
下面将在源文件中找到字符串并输出带有插入的新文件。
:: Hide Command and Isolate Scope with Command Extensions
@echo off
setlocal EnableExtensions DisableDelayedExpansion
:: See the following for help
rem echo /?
rem setlocal /?
rem for /?
rem type /?
rem find /?
rem del /?
:: Setup
set "xIn=Test.xml"
set "xOut=Output.xml"
set "xTerm=<Tools>"
set "xInsert=^<HELLO WORLD^>"
:: Validate
if not defined xIn goto End
if not defined xOut goto End
:: Place on Seperate Line Method
if defined xOut if exist "%xOut%" del /f /q "%xOut%" > nul
for /f "usebackq tokens=*" %%a in (`type %xIn%`) do (
echo.%%a >> %xOut%
for /f "usebackq tokens=*" %%x in (`echo."%%a" ^| find "%xTerm%"`) do (
echo.%xInsert% >> %xOut%
)
)
:: Setup
set "xOut=Output2.xml"
:: Validate
if not defined xOut goto End
:: Place on the Same Line Method
if defined xOut if exist "%xOut%" del /f /q "%xOut%" > nul
for /f "usebackq tokens=*" %%a in (`type %xIn%`) do (
for /f "usebackq tokens=*" %%x in (`echo."%%a" ^| find /v "%xTerm%"`) do (
echo.%%a >> %xOut%
)
for /f "usebackq tokens=*" %%x in (`echo."%%a" ^| find "%xTerm%"`) do (
echo.%%a %xInsert% >> %xOut%
)
)
:End
endlocal
编辑:这是上述脚本的修改版本,它将用文件内容替换包含搜索词的行。它应该可以很好地处理报价。请参阅脚本中的 call 命令以了解如何使用它。
:: Hide Command
@echo off
set "xResult="
call :ReplaceWith xResult "Source.xml" "<Tools>" "Input.xml" "Output.xml"
echo.%xResult%
goto End
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:ReplaceWith <xReturn> <Source File> <Search Term> <Input File> <Output File>
:: Replace a line in the source file containing the search term with the entire
:: contents of the input file and save the changes to the output file.
:::: Note: Only supports single line search terms.
:: Returns the number of lines replaced. -1 for error.
:: Hide Commands, Isolate Scope, and Set Abilities
@echo off
setlocal EnableExtensions DisableDelayedExpansion
:: Setup
set "xResult=-1"
set "xSource=%~2"
set "xTerm=%~3"
set "xInput=%~4"
set "xOut=%~5"
:: Validate
if not defined xSource goto EndReplaceWith
if not exist "%xSource%" goto EndReplaceWith
if not defined xTerm goto EndReplaceWith
if not defined xInput goto EndReplaceWith
if not exist "%xInput%" goto EndReplaceWith
set "xResult=0"
:: Search
type nul > %xOut%
for /f "usebackq tokens=* delims=" %%a in (`type "%xSource%"`) do (
for /f "usebackq tokens=*" %%x in (`echo."%%a" ^| find /v "%xTerm%"`) do (
echo.%%a>> %xOut%
)
for /f "usebackq tokens=*" %%x in (`echo."%%a" ^| find "%xTerm%"`) do (
type "%xInput%" >> %xOut%
echo.>> %xOut%
set /a "xResult+=1"
)
)
:EndReplaceWith
endlocal & if not "%~1"=="" set "%~1=%xResult%"
goto :eof
:: by David Ruhmann
:End
endlocal