Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to extract the lines containing PAT1 but not PAT2 from a file. For example, with PAT1='dog', PAT2='cat', and the following input:

1 cat chicken
2 bird dog apple
3 dog orange cat
4 cat juice coffee
5 cow milk dog

I want the following output:

2 bird dog apple
5 cow milk dog
share|improve this question

Something like:

sed '/dog/!d;/cat/d'

See also

grep dog | grep -v cat
share|improve this answer
Grep is the first thing I thought of, is there another reason you needed sed? – Yuugian Nov 20 '12 at 14:42

You can do it like this :

sed -n '
' file.txt

or with :

awk '/dog/ && !/cat/' file.txt

later one have the advantage to be very clear & simple to remember.

or using

perl -ne 'print if /dog/ && !/cat/' file.txt
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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