batch-file File Handling in batch files Editing Nth Line of a File


Batch file does not come with a built-in method for replacing nth 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%"
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

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

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

    • It loops through all the lines and echo them to a temporary file before the replacement line
    • It echoes the replacement line to the file
    • It continues to output to rest of the file
    • It copies the temporary file to the original file
    • And removes the temporary file.
  • The main script gets the control back, and type the result.