How can you grep for three fields

I have data, from which I want to grep for two fields. Only pull out the data if both the fields exist.

I have used: egrep --text "field1|field2" file > temp. This seems to be doing an OR. What I am after is an AND.

When you have the "|" in your command, that is telling the system to do OR logic.

The typical AND logic for grep is to simply complete two greps. Something like the following:

cat myfile | grep "text1" | grep "text2" >newfile

You can also use awk :

awk '/text1/ && /text2/' file > newfile

Jean-Pierre.

Be careful or the "don't cat to grep" mafia is going to get you...

It can just be kind of difficult for some to understand the following:

grep "text1" <myfile | grep "text2" >newfile

So, while some might 'herd' that 'cat' - I was simply trying to show a sample of multiple greps.

Why run grep twice :rolleyes: UUOG

grep "text1.*text2" myfile > newfile

What about lines containing text2 before text1 ?

Jean-Pierre.

:slight_smile: that's another story, let's try awk

awk '/text1/ && /text2/' file

For two fields it could be something like this:

egrep 'text1.*text2|text2.*text1' filename

For more than two another tool should be used.

grep -e 'string1' -e 'string2' filename >newfilename

The title of the thread is How can you grep for three fields
We can use grep (faster) but I like awk(slower).

egrep 'text1.*text2.*text3|text1.*text3.*text2|text2.*text1.*text3|text2.*text3.*text1|text3.*text2.*text1|text3.*text1.*text2' file

No-Go ;), you should read carefully the OP request.
He need "pattern1" AND "pattern2" Not "pattern1" OR "pattern2".