I want to extract the lines that matches the following logical operation:

"AB+CD" AND ("nonAB+nonCD" OR "nonAB+CD"). 

Which means I want lines with:


Meaning that I am looking for lines with "AB+CD" with one or both of ("nonAB+nonCD" OR "nonAB+CD").
Note that the + is part of the string. I want to treat it as a string (character) not arithmetic operation.

What I did is using pipe to execute AND. And use \| for the OR. So My command is:

grep ',AB+CD' test.txt | grep ',nonAB+nonCD\|,nonAB+CD'

The first | is for piping. The second is logical OR for grep as per this reference that gives this example for logical OR with grep:

grep 'pattern1\|pattern2' filename

The result that appears to me in the terminal colors (finds) the second part of the command. The first part (before the pipe | is not highlighted in the colored result. My question:

1) Is my command correct?

2) How to color the complete command findings?

  • The escape sequences for colouring the output are generated only on terminal output: if passed into a pipe, they could interfere with a subsequent match. You would therefore need to make the whole match with a single grep call. This should be possible with grep -E (or egrep), and I'll have a look at a possible match string. In your examples, AB+CD precedes nonAB: is this always the case? Your double search will match, even if AB+CD comes later. – AFH Jun 9 '18 at 11:33
  • No specific order in my case. Just AB+CD is a must. Then the others ,nonAB+nonCD or ,nonAB+CD at least one of them need to be matched. – user9371654 Jun 9 '18 at 11:38
  • Some initial tests show that the match will need to take the form pattern1.*pattern2, which means that all the intermediate characters between the two patterns will be part of the match and therefore coloured. Will this be satisfactory? – AFH Jun 9 '18 at 11:51

Using -P option (PCRE):

grep -P 'AB\+CD,(?:nonAB\+nonCD|nonAB\+CD)' file.txt



Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.