Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use grep to match two strings in the same line

Tags:

string

grep

bash

How can I use grep to find two terms / strings in one line?
The output, or an entry in the log file, should only be made if the two terms / strings have been found.
I have made the following attempts:

egrep -n --color '(string1.*string2)' debuglog.log

In this example, everything between the two strings is marked.
But I would like to see only the two found strings marked.
Is that possible?
Maybe you could do this with another tool, I am open for suggestions.

like image 883
webuser57 Avatar asked Oct 17 '25 11:10

webuser57


2 Answers

The simplest solution would be to first select only the lines that contain both strings and then grep twice to color the matches, eg:

egrep 'string1.*string2|string2.*string1' |
    egrep -n --color=always 'string1' | egrep --color 'string2'

It is important to set color to always, otherwise the grep won't output the color information to the pipe.

like image 81
Dzienny Avatar answered Oct 19 '25 02:10

Dzienny


I know some people will disagree, but I think the best way is to do it like this :

Lets say this is your input :

$ cat > fruits.txt
apple banana
orange strawberry
coconut watermelon
apple peach

With this code you can get exactly what you need, and the code looks nicer and cleaner :

awk '{ if ( $0 ~ /apple/ && $0 ~ /banana/ ) 
       { 
         print $0
       } 
    }' fruits.txt

But, as I said before, some people will disagree as its too much typing. ths short way with grep is just concatenate many greps , e.g. :

grep 'apple' fruits.txt | grep 'banana'

Regards!

like image 40
Matias Barrios Avatar answered Oct 19 '25 04:10

Matias Barrios



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!