Skip to content

Instantly share code, notes, and snippets.

@davidruhmann
Created December 8, 2012 01:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidruhmann/4238166 to your computer and use it in GitHub Desktop.
Save davidruhmann/4238166 to your computer and use it in GitHub Desktop.
[Batch] Replace a line in a file containing the term with the entire contents of the input file.
:: Hide Command
@echo off
set "xResult="
::if exist "Output.xml" del /f /q "Output.xml"
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
::if not defined xOut set "xOut=%~2"
::if not exist "%xOut%" 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
:End
endlocal
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment