windows – 批处理脚本,用于在文本文件中打印上一行和下一行搜索字符串

前端之家收集整理的这篇文章主要介绍了windows – 批处理脚本,用于在文本文件中打印上一行和下一行搜索字符串前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个批处理脚本,它将整行搜索字符串打印到一个文本文件中.
for %%i in (log.txt) do (
FINDSTR /G:pattern.txt %%i >> output.txt
)

例:
pattern.txt包含搜索字符串ERROR,以下是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

只要在log.txt中找到字符串ERROR,上面的批处理脚本就会打印每行文本.所以,output.txt看起来会有如下所示的行

2013-06-30 02:17:55,578 ERROR  error occurred and message is ""

如何只打印上一行和下一行搜索字符串,如下所示:

2013-06-30 02:17:55,578 DEBUG  bit version: 8

提前致谢.

@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
原文链接:https://www.f2er.com/windows/372211.html

猜你在找的Windows相关文章