4

我有一个批处理脚本,它将整行搜索字符串打印到一个文本文件中。

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  Element value: 1
2013-06-30 02:17:55,578 DEBUG  bit version: 8

提前致谢。

4

3 回答 3

4
@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
于 2013-07-30T18:55:36.270 回答
3

这使用了一个名为 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%"
于 2013-07-30T08:40:14.890 回答
1

尝试这个:

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
)
于 2013-07-30T07:15:45.607 回答