@DennisvanGils' approach is a good start and will do well in many cases.
However, it will not produce an exact copy of the text file content between the given lines:
- leading whitespaces (SPACE and TAB) will be removed (due to
tokens=*
option),
- lines starting with
;
will be skipped (due to the default option eol=;
of for /F
), and
- empty lines will be skipped as well (as
for /F
always skips such).
To get an exact copy of the text file portion, you could use the following code snippet:
@echo off
set "INFILE=M:\TESTING\input.txt"
set "OUTFILE=M:\TESTING\output.txt"
set "FIRSTLINE=------------------------------------------------------------------------------------------------------------------"
set "LASTLINE=*******************************************************************************************************************"
setlocal EnableExtensions DisableDelayedExpansion
set "FLAG="
> "%OUTFILE%" (
for /F "delims=" %%L in ('findstr /N "^" "%INFILE%"') do (
set "LINE=%%L"
setlocal EnableDelayedExpansion
set "LINE=!LINE:*:=!"
if "!LINE!"=="%FIRSTLINE%" (
endlocal
set "FLAG=TRUE"
) else if "!LINE!"=="%LASTLINE%" (
endlocal
goto :CONTINUE
) else if defined FLAG (
echo(!LINE!
endlocal
) else (
endlocal
)
)
)
:CONTINUE
endlocal
Core function here is findstr
, which is configured so that every line in the file is returned, prefixed with a line number and a colon :
. Its output is then parsed by a for /F
loop. Because of the prefix, no line appears to be empty and therefore every one is iterated by the loop. In the body of the loop, the prefix is removed by the set "LINE=!LINE:*:=!"
command for each line.
The variable FLAG
is used to decide whether or not the current line is to be output; if it is defined, that is, a value is assigned, the command echo !LINE!
is executed; otherwise it is not. FLAG
is set if the current line matches the string in %FIRSTLINE%
; if the line matches the string in %LASTLINE%
, a goto
command is executed which breaks the loop. This means also that only the first block between %FIRSTLINE%
and %LASTLINE%
matches is output.
If there might occur multiple %FIRSTLINE%
and %LASTLINE%
matches within the text file and you want to output every block, replace the goto
command line by set "FLAG="
.
Note that this approach does not check whether %FIRSTLINE%
occurs before %LASTLINE%
, nor does it even check for existence of %LASTLINE%
(all remaining lines to the end of file are output in case). If all this is important, the logic need to be improved and even a second loop will be required most likely.