Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I tail -f a log and only print certain lines matching some text?

Tags:

grep

bash

I'd like to tail a log, find some text and only output the the line found plus the next line, is it possible?

THE QUICK 
BROWN FOX 
JUMPED OVER
THE LAZY 
DOG'S BACK

Something like: tail -f | grep BROWN FOX

output would be:

BROWN FOX 
JUMPED OVER
like image 435
Adam M Avatar asked Sep 13 '25 04:09

Adam M


2 Answers

tail -<num1> filename.log | grep "search_string" -A num2

Example file: a.log

10 20
10 12
11 14


tail -2 a.log | grep "10" -A 1 # tail -2 indicates two lines from the end of the file


Output

10 12
11 14

Grep options
Use -n option in grep to print line number
Use -C num option to get leading and trailing context(adjacent lines to the matching one)
Use -A num option to get trailing num of lines Use -B num option to get leading num of lines

like image 157
shirish Avatar answered Sep 16 '25 08:09

shirish


 tail -f log_file_name | grep --line-buffered -A1 BROWN FOX

--line-buffered causes grep to respond more promptly to the piped input (very useful if the log file grows slowly)

-A1 asks it to also display one line after each match.

like image 31
Jasen Avatar answered Sep 16 '25 09:09

Jasen