Sam
Sam

Reputation: 4487

Pattern matching logs in ubuntu

myfile.log contains things like:

----- 12:08:12 (123.123.123.123) --------------------------------
Some code here...
This section has no specified length...
-----------------------------------------------------------------


----- 12:10:15 (254.14.187.123) --------------------------------
Some code here...
This section has no specified length...
It could be 3 lines, or 4 lines, or 20 lines. 
-----------------------------------------------------------------

I want to use something like grep to pull out every block that contains the IP address 123.123.123.123. For example, the following would be returned:

----- 12:08:12 (123.123.123.123) --------------------------------
Some code here...
This section has no specified length...
-----------------------------------------------------------------

Edit: Thanks for the answers so far, I forgot to mention that I need it to stream the output in the same way tail would.

Upvotes: 0

Views: 171

Answers (3)

knittl
knittl

Reputation: 265241

I would use something similar to:

sed -n '/^-----.*(123\.123\.123\.123) ---/,/^------/p' file.log

It first matches a line, starting with 5 hyphens, then contains a number of arbitrary characters, then the IP address enclosed in parentheses, followed by some hyphens. Then it matches all lines until it encounters a line that starts with 5 hyphens. You could use /^-\{5,\}$/ to specify a line that contains hyphens only (at least 5).

Regarding the edit on your question: with streaming I assume you mean tail -f? Simply pipe its output into sed:

tail -f file.log | sed -n '/^-----.*(123\.123\.123\.123) ---/,/^------/p'

Upvotes: 2

Eugene S
Eugene S

Reputation: 6910

You can use grep -A <NUM>. This will print NUM lines of trailing context after matching lines

Upvotes: 0

Kent
Kent

Reputation: 195079

does this give you what you want?

sed -n '/123\.123\.123\.123/,/^-*$/{p}' yourFile

Upvotes: 1

Related Questions