Search code examples
bashgrepgnu-coreutils

Check if file contains string1 AND NOT string2


I've got a program (prog) that takes a lot of time to produce its output.

I need to check if the output contains string1 and not string2.

Right now I do the following. It invokes prog 2 times.

if   prog | grep -q 'some string' &&
   ! prog | grep -q 'another string'; then
    echo 'OK'
else
    echo 'Not OK'
fi

Is there are way to do this with only 1 invocation of prog?

Any solution involving awk or sed will do as well.

UPDATE

What I was hoping for was a one liner—that my mind cannot see—to do the trick, having GNU coreutils at my disposal.


Solution

  • I don't think it is possible with grep without executing prog twice, or better, saving it's output into a temporary file.

    I would recommend to use awk:

    awk '/string1/{a=1}/string2/{b=1}END{exit !a && b}'
    

    You can use it in the shell script like:

    if prog | awk '/string1/{a=1}/string2/{b=1}END{exit !a && b}' ; then
        echo "ok"
    else
        echo "not ok"
    fi
    

    Note: awk treats 0 as false and 1 as true. The shell treats 0 as true and 1 as false. To reflect that we return !a && b instead of the a && !b, which might look more reasonable in the first place.