Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you grep a file using a regular expression and only output the matching part of a line?

Tags:

grep

shell

unix

I have a log file which contains a number of error lines, such as:

Failed to add [email protected] to database

I can filter these lines with a single grep call:

grep -E 'Failed to add (.*) to database'

This works fine, but what I'd really like to do is have grep (or another Unix command I pass the output into) only output the email address part of the matched line.

Is this possible?

like image 834
Olly Avatar asked Jun 10 '09 10:06

Olly


People also ask

How do you use grep in regular expressions?

Grep Regular Expression In its simplest form, when no regular expression type is given, grep interpret search patterns as basic regular expressions. To interpret the pattern as an extended regular expression, use the -E ( or --extended-regexp ) option.

How do I print only the grep matching string?

Displaying only the matched pattern : By default, grep displays the entire line which has the matched string. We can make the grep to display only the matched string by using the -o option.

Which option of the grep command prints only a count of the lines that match a pattern?

The -c option tells grep to supress the printing of matching lines, and only display the number of lines that match the query. For instance, the following will print the number 4, because there are 4 occurences of "boo" in a_file. An option more useful for searching through non-code files is -i, ignore case.

How do you grep for a word and display only the word?

The easiest of the two commands is to use grep's -w option. This will find only lines that contain your target word as a complete word. Run the command "grep -w hub" against your target file and you will only see lines that contain the word "hub" as a complete word.


2 Answers

sed is fine without grep:

sed -n 's/Failed to add \(.*\) to database/\1/p' filename
like image 109
Maciej Łebkowski Avatar answered Oct 19 '22 07:10

Maciej Łebkowski


You can also just pipe grep to itself :)

grep -E 'Failed to add (.*) to database' | grep -Eo "[^ ]+@[^ ]+"

Or, if "lines in interest" are the only ones with emails, just use the last grep command without the first one.

like image 39
Valentin Avatar answered Oct 19 '22 07:10

Valentin