Saturday, April 9, 2022

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

Issue

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?


Solution

You can use sed:

grep -E 'Failed to add (.*) to database'| sed 's/'Failed to add \(.*\) to database'/\1'


Answered By - Nathan Fellman
Answer Checked By - Mildred Charles (WPSolving Admin)