简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM