简体   繁体   中英

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

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.

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.

Here is single command awk solution that prefixes and suffixes matched strings with color codes:

awk '/string1.*string2/{
gsub(/string1|string2/, "\033[01;31m\033[K&\033[m"); print}' file

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 , eg :

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

Regards!

I am a little confused of what you really want as there was no sample data or expected output, but:

$ cat foo
1
2
12
21
132
13

And the awk that prints the matching parts of the records:

$ awk '
/1/ && /2/ {
    while(match($0,/1|2/)) {
        b=b substr($0,RSTART,RLENGTH)
        $0=substr($0,RSTART+RLENGTH)
    }
    print b
    b=""
}' foo
12
21
12

but fails with printing overlapping matches.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM