Search code examples
batch-filetextcmdedit

How do i add multiple lines after a certain line in a text file using batch


I need to edit a text file to insert multiple lines after a certain line with only features that come with windows 10

example: Insert the lines foo and bar after line 4

text file example before additions:

line 1
line 2
line 3
line 4
line 5
line 6

text file example after additions:

line 1
line 2
line 3
line 4
foo
bar
line 5
line 6

Solution

  • Read the file and write it back, insert the new lines at a specific lineno.

    @echo off
    
    setlocal DisableDelayedExpansion
    set randomline=4
    set "lineno=0"
    (
        FOR /F "delims=" %%L in ('findstr /n "^" sample.txt') do (
            set /a lineno+=1
            set "line=%%L"
            setlocal EnableDelayedExpansion        
            if "!lineno!"=="%randomline%" call :insertblock
            set "line=!line:*:=!"
            (echo(!line!)
            endlocal
        )
    ) > output.txt
    exit /b
    
    :insertblock
    echo foo
    echo bar
    exit /b