下面的批处理文件提取一系列行:从第一个字符串的第一次出现到第二个字符串的最后一次出现,或多行:
@echo off
setlocal DisableDelayedExpansion
if "%~3" neq "" goto start
echo Show a range of lines, from "start string" to "end string" or number of lines
echo/
echo ShowRange.bat inputfile "start string" "end string"
echo ShowRange.bat inputfile "start string" /N:24
goto :EOF
:start
set end=%~3
if /I "%end:~0,3%" neq "/N:" (
for /F "delims=:" %%a in ('findstr /N /C:%2 /C:%3 %1') do (
if not defined start (
set /A start=%%a-1
) else (
set end=%%a
)
)
set /A lines=end-start
) else (
for /F "delims=:" %%a in ('findstr /N /C:%2 %1') do (
if not defined start set /A start=%%a-1
)
set lines=%end:~3%
)
if %start% neq 0 set skip=skip=%start%
for /F "%skip% delims=" %%a in ('findstr /N "^" %1') do (
set "line=%%a"
setlocal EnableDelayedExpansion
set "line=!line:*:=!"
echo(!line!
set /A lines-=1
if "!lines!" equ "0" goto :EOF
for /F %%b in ("!lines!") do endlocal & set lines=%%b
)
例如:
set /? > set.txt
ShowRange.bat set.txt "Environment variable substitution" "would extract"
ShowRange.bat set.txt "Environment variable substitution" /N:24
编辑:下面的版本从 STDIN 读取输入,因此可以与管道一起使用,但速度较慢,因为它必须在每个输入行中实现“查找字符串”部分:
@echo off
setlocal DisableDelayedExpansion
if "%~2" neq "" goto start
echo Show a range of lines, from "start string" to "end string" or number of lines
echo/
echo command ^| ShowRangePipe.bat "start string" "end string"
echo command ^| ShowRangePipe.bat "start string" /N:24
goto :EOF
:start
set startFound=no
set end=%~2
if /I "%end:~0,3%" neq "/N:" (
for /F "delims=" %%a in ('findstr /N "^"') do (
set "line=%%a"
setlocal EnableDelayedExpansion
set "line=!line:*:=!"
if "!startFound!" equ "no" (
if defined line if "!line:%~1=!" neq "!line!" set startFound=yes & echo !line!
) else (
echo(!line!
if defined line if "!line:%~2=!" neq "!line!" goto :EOF
)
for /F %%b in ("!startFound!") do endlocal & set startFound=%%b
)
) else (
set /A lines=%end:~3%-1
for /F "delims=" %%a in ('findstr /N "^"') do (
set "line=%%a"
setlocal EnableDelayedExpansion
set "line=!line:*:=!"
if "!startFound!" equ "no" (
if defined line if "!line:%~1=!" neq "!line!" set startFound=yes & echo !line!
) else (
echo(!line!
set /A lines-=1
if "!lines!" equ "0" goto :EOF
)
for /F "tokens=1,2" %%b in ("!startFound! !lines!") do endlocal & set "startFound=%%b" & set lines=%%c
)
)
例如:
set /? | ShowRangePipe.bat "Environment variable substitution" "would extract"
set /? | ShowRangePipe.bat "Environment variable substitution" /N:24