Windows Batch操作找到含字符串行并打印本行及后两行
Posted scruffybear
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Windows Batch操作找到含字符串行并打印本行及后两行相关的知识,希望对你有一定的参考价值。
文章目录
小结
需要Windows Batch操作找到含字符串行并打印本行及后两行,找到办法并解决
问题及解决
有关回车换行的处理
回车换行是特殊字符,如果需要查找连续多行所包含的字符,需要处理回国换行符,参考Stackoverflow:What are the undocumented features and limitations of the Windows FINDSTR command?
由于正则表达式不会匹配 CR
和 LF
,需要进行特殊操作显式匹配,如果多行匹配了,只打印第一行。
TEXT.TXT
文本包括以下内容
A
A
A
B
A
A
使用以下脚 本:
@echo off
setlocal
::Define LF variable containing a linefeed (0x0A)
::得到换行符Line Feed[行满]
set LF=^
::Above 2 blank lines are critical - do not remove
::Define CR variable containing a carriage return (0x0D)
::得到回车符Carriage Return, 导入之后使用约定变量CR, 调用者开启延迟变量使用[!CR!], 未开启延迟变量无法调用。所以copy /z到nul会生成一个CR字符。
for /f %%a in ('copy /Z "%~dpf0" nul') do set "CR=%%a"
setlocal enableDelayedExpansion
::regex "!CR!*!LF!" will match both Unix and Windows style End-Of-Line
findstr /n /r /c:"A!CR!*!LF!A" TEST.TXT
输出连续两行有字母A
的结果如下:
1:A
2:A
5:A
循环并输出找到的所有行
循环并输出找到的所有行包括字符E000
,打印本行,并打印找到的行的下两行。
@echo off
setlocal enableDelayedExpansion
rem Assemble the list of line numbers
set numbers=
for /F "delims=:" %%a in ('findstr /N /L "E000" test.txt') do (
set /A current=%%a
echo var1: !current!
set /A before=%%a+1
set /A after=%%a+2
set "numbers=!numbers!!current!: !before!: !after!: "
)
echo !numbers!
rem Search for the lines
for /F "tokens=1* delims=:" %%a in ('findstr /N "^" test.txt ^| findstr /B "%numbers%"') do echo %%b
以上,如果test.txt文件过大,则这个脚本就会不能运行。
参考
FOR /FLoop command
COPY Copy one or more files to another location.
FOR Conditionally perform a command several times.
FINDSTR Search for a text string in a file (or multiple files)
Stackoverflow:What are the undocumented features and limitations of the Windows FINDSTR command?
Stackoverlfow: What does %~d0 mean in a Windows batch file?
Stackoverflow: batch script to print previous and next lines of search string in a text file
Alternate method to get TAB, Carriage return and possibly all others
以上是关于Windows Batch操作找到含字符串行并打印本行及后两行的主要内容,如果未能解决你的问题,请参考以下文章