批处理脚本在文本文件中打印searchstring的前一行和下一行

我有一个批处理脚本,将整个searchstring打印到一个文本文件

for %%i in (log.txt) do ( FINDSTR /G:pattern.txt %%i >> output.txt ) 

例如:pattern.txt包含searchstringERROR ,下面是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中findstringERROR时候打印每行文本。所以,output.txt看起来像下面的行

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

我怎样才能打印只有像下面的searchstring的前一行和下一行:

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

这使用了一个名为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%" 

尝试这个:

 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 )