NeverPhased
NeverPhased

Reputation: 1566

How can I use grep to return the full string of text that a searched term is nested in?

Lets say I have the following text:

Hi my name is Larry and this is my profile www.cool.com/imgreat please check it out.

egrep -i --color 'cool' filename

Just highlights the occurrence of 'cool' in the string but I would like it to return 'www.cool.com/imgreat'

Upvotes: 1

Views: 99

Answers (3)

Inian
Inian

Reputation: 85560

You can use a simple awk to loop through the entries one by one and if any of the row entries match cool print the whole word.

$ string="Hi my name is Larry and this is my profile www.cool.com/imgreat please check it out"
$ awk '{for(i=1;i<=NF;i++) {if ($i ~ /cool/){print $i}}}' <<<"$string"
www.cool.com/imgreat

Upvotes: 1

Fredrik Pihl
Fredrik Pihl

Reputation: 45652

If you would like to extract the part containing cool delimited by WS, you can use awk

$ awk '{for(i=1;i<NF;i++) if ($i ~ /cool/)print $i}' <<< """Hi my name is Larry and this is my profile www.cool.com/imgreat please check it out."""
www.cool.com/imgreat

Upvotes: 1

Andrea De Luca
Andrea De Luca

Reputation: 127

Try this one, this should be the regex that match the pattern of a website (this does not comprend http/https): [-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&=]*) So your command should be:

    egrep -i --color '[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&=]*)' filename

Upvotes: 1

Related Questions