I want to search for "STRING1" using grep but to skip if the line contains "STRING2". How can I do it?


This will do:

 grep -v "STRING2" file | grep "STRING1"
  • 1
    guillermo chamorro's answer is more efficient that searching for STRING1 then discarding the result if STRING2 is present. – K7AAY Nov 13 at 22:11

You might want to consider using awk or perl instead of grep


awk '/STRING1/ && !/STRING2/' file


perl -ne 'print if /STRING1/ && !/STRING2/' file

See also grep with logic operators .

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.