windows 批处理脚本打印文本文件中搜索字符串的上一行和下一行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17940198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 10:45:43  来源:igfitidea点击:

batch script to print previous and next lines of search string in a text file

windowsfiletextbatch-file

提问by Shrik

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 ERRORand below is the sample text in log.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

The above batch script will print each line of text whenever it finds the string ERRORin log.txt So, the output.txt will look have lines like below

每当ERROR在 log.txt 中找到字符串时,上面的批处理脚本将打印每一行文本,因此,output.txt 将具有如下所示的行

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.

提前致谢。

采纳答案by Aacini

@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

回答by foxidrive

This uses a helper batch file called findrepl.bat from - http://www.dostips.com/forum/viewtopic.php?f=3&t=4697

这使用了一个名为 findrepl.bat 的辅助批处理文件 - http://www.dostips.com/forum/viewtopic.php?f=3&t=4697

@echo off
set "var=searchterm"
type "file.txt"|findrepl "%var%" /o:-1:+1 |find /v "%var%"

回答by Endoro

try this:

尝试这个:

for /f "delims=:" %%a in ('findstr /in "error" log.txt') do set /a found=%%a
if not defined found (echo "error" not found&goto:eof)
set /a line1=found-1
set /a line2=found+1
for /f "tokens=1*delims=:" %%a in ('findstr /in "^" log.txt') do (
    if %%a==%line1% >>output.txt echo(%%b
    if %%a==%line2% >>output.txt echo(%%b
)