Batch file does not come with a built-in method for replacing n
th line of a file except replace
and append
(>
and >>
). Using for
loops, we can emulate this kind of function.
@echo off
set file=new2.txt
call :replaceLine "%file%" 3 "stringResult"
type "%file%"
pause
exit /b
:replaceLine <fileName> <changeLine> <stringResult>
setlocal enableDelayedExpansion
set /a lineCount=%~2-1
for /f %%G in (%~1) do (
if !lineCount! equ 0 pause & goto :changeLine
echo %%G>>temp.txt
set /a lineCount-=1
)
:changeLine
echo %~3>>temp.txt
for /f "skip=%~2" %%G in (%~1) do (
echo %%G>>temp.txt
)
type temp.txt>%~1
del /f /q temp.txt
endlocal
exit /b
The main script calls the function replaceLine
, with the filename/ which line to change/ and the string to replace.
Function receives the input
echo
them to a temporary file before the replacement lineecho
es the replacement line to the fileThe main script gets the control back, and type
the result.