我有一个批处理脚本,它会将整行搜索字符串打印成文本文件。
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
提前致谢。
答案 0 :(得分: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
答案 1 :(得分:3)
这使用了来自 - http://www.dostips.com/forum/viewtopic.php?f=3&t=4697
的名为findrepl.bat的帮助程序批处理文件@echo off
set "var=searchterm"
type "file.txt"|findrepl "%var%" /o:-1:+1 |find /v "%var%"
答案 2 :(得分: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
)