简体   繁体   中英

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

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 ERROR and below is the sample text in 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 ERROR in log.txt So, the output.txt will look have lines like below

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.

@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

This uses a helper batch file called findrepl.bat from - 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%"

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
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM