2013-07-30 63 views
2

我有一個批處理腳本,它將整行搜索字符串打印到文本文件中。批處理腳本在文本文件中打印搜索字符串的前一行和下一行

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 

上述批次腳本將打印的每一行文本每當找到字符串ERROR在log.txt中那麼,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
@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 
+0

增加了兩行來產生output.txt'rem爲/ F「tokens = 1 * delims =:」%% a行搜索行 ('findstr/N「^」log.txt^| findstr/B「 %數字%「')do( \t if %% a ==%before%>> output.txt echo %% b \t if %% a ==%%>> output.txt echo %% b ) '適用於多個搜索字符串,如「發生錯誤」。但只打印最後一次出現。在實時場景中,搜索字符串會出現多次。沒有使用第三方工具可以實現嗎? – Shrik

+0

原始代碼搜索所有出現的字符串。你沒有測試過嗎?如果你想產生output.txt文件,只需用這種方法把最後一行括起來:'('original last line')> output.txt'。我已經修改了上面這種方式的代碼... – Aacini

+0

真棒Aacini。抱歉。我修改生成output.txt文件的代碼只搜索最後一次出現。你最新的代碼工作正常。 – Shrik

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 
) 
+0

拋出錯誤: 「在在這個時候意外」 第二(''for'loop'for/f「tokens = 1 * delims =:」in('findstr/in「^」ATServer-webconsole.log')do(' – Shrik

+0

Endoro錯過了'%% a':'for/f 「tokens = 1 * delims =:」%% a in('findstr/in「^」log.txt')do(' – Stephan

+0

@St ephan Right。跨越還有兩個障礙。 1.它僅打印最後一次搜索字符串。 2.不適用於包含兩個或更多單詞(例如'ISSUE DETECTED')的搜索字符串。 output.txt不會生成。顯示沒有錯誤。 – Shrik

相關問題