Windows Batch操作找到含字符串行并打印本行及后两行

小结

需要Windows Batch操作找到含字符串行并打印本行及后两行,找到办法并解决

问题及解决

有关回车换行的处理

回车换行是特殊字符,如果需要查找连续多行所包含的字符,需要处理回国换行符,参考Stackoverflow:What are the undocumented features and limitations of the Windows FINDSTR command?

由于正则表达式不会匹配 CRLF,需要进行特殊操作显式匹配,如果多行匹配了,只打印第一行。

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值