Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
add comment

2 Answers

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
add comment

You can do it like this :

sed -n '
    /dog/{
        /cat/!{
            p
        }
    }
' 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
add comment

Your Answer

 
discard

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.