批处理脚本打印previous和搜索字符串的下一行的文本文件 [英] batch script to print previous and next lines of search string in a text file
本文介绍了批处理脚本打印previous和搜索字符串的下一行的文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个批处理脚本,它将打印搜索字符串的整条生产线到一个文本文件中。
为%%我在(log.txt的)做(
FINDSTR /G:pattern.txt %% I>> output.txt的
)
例如:
pattern.txt包含搜索字符串错误
以下是log.txt的示例文本
2013-06-30 02:17:55562信息服务开始
2013-06-30 02:17:55578信息发送邮件...
2013-06-30 02:17:55578元DEBUG值:1
发生55578错误错误和消息是:2013-06-30 02:17
2013-06-30 02:17:55578 DEBUG位版本:8
2013-06-30 02:17:55578信息服务已停止
以上批处理脚本将打印文本的每一行只要找到字符串错误
在log.txt中因此,output.txt的看起来有像下面线p>
2013-06-30 02:发生55578错误错误和消息是:17
我怎么能只打印previous和搜索字符串的下一行象下面这样:
2013-06-30 02:17:55578元DEBUG值:1
2013-06-30 02:17:55578 DEBUG位版本:8
先谢谢了。
解决方案
关闭@echo
SETLOCAL EnableDelayedExpansion
REM组装线编号列表
组号码=
FOR / Fdelims =%%一个在('FINDSTR / I / N / C:发生错误的log.txt')做(
设置/ A = %% A-1之前,之后= %%一个+ 1
设置数字=!号!以前!:!之后!:
)
对于线REM搜索
(FOR / F令牌= 1 * delims =%%一个在('FINDSTR / N^log.txt的^ | FINDSTR / B%数%')做回声%% B)> output.txt的
I have a batch script which will print the entire line of search string into a text file.
for %%i in (log.txt) do (
FINDSTR /G:pattern.txt %%i >> output.txt
)
Example:
pattern.txt contains search string ERROR
and below is the sample text in log.txt
2013-06-30 02:17:55,562 INFO Service started
2013-06-30 02:17:55,578 INFO Sending mail...
2013-06-30 02:17:55,578 DEBUG Element value: 1
2013-06-30 02:17:55,578 ERROR error occurred and message is ""
2013-06-30 02:17:55,578 DEBUG bit version: 8
2013-06-30 02:17:55,578 INFO Service stopped
The above batch script will print each line of text whenever it finds the string ERROR
in log.txt So, the output.txt will look have lines like below
2013-06-30 02:17:55,578 ERROR error occurred and message is ""
How can I print only previous and next lines of search string like below:
2013-06-30 02:17:55,578 DEBUG Element value: 1
2013-06-30 02:17:55,578 DEBUG bit version: 8
Thanks in advance.
解决方案
@echo off
setlocal EnableDelayedExpansion
rem Assemble the list of line numbers
set numbers=
for /F "delims=:" %%a in ('findstr /I /N /C:"error occurred" log.txt') do (
set /A before=%%a-1, after=%%a+1
set "numbers=!numbers!!before!: !after!: "
)
rem Search for the lines
(for /F "tokens=1* delims=:" %%a in ('findstr /N "^" log.txt ^| findstr /B "%numbers%"') do echo %%b) > output.txt
这篇关于批处理脚本打印previous和搜索字符串的下一行的文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文