How to use grep when file does not contain the string

126,798

Solution 1

grep will return success if it finds at least one instance of the pattern and failure if it does not. So you could either add an else clause if you want both "does" and "does not" prints, or you could just negate the if condition to only get failures. An example of each:

if grep -q "$user2" /etc/passwd; then
    echo "User does exist!!"
else
    echo "User does not exist!!"
fi

if ! grep -q "$user2" /etc/passwd; then
    echo "User does not exist!!"
fi

Solution 2

You can use the grep option "-L / --files-without-match", to check if file does not contain a string:

if [[ $(grep -L "$user2" /etc/passwd) ]]; then   
  echo "User does not exist!!"; 
fi

Solution 3

An alternative is to look for the exit status of grep. For example:

grep -q "$user2" /etc/passwd
if [[ $? != 0 ]]; then
    echo "User does not exist!!"

If grep fails to find a match it will exit 1, so $? will be 1. grep will always return 0 if successful. So it is safer to use $? != 0 than $? == 1.

Solution 4

grep -q query_text ./file.txt && echo true || echo false

Solution 5

I solve it with simple one liner:

for f in *.txt; do grep "tasks:" $f || echo $f; done

The command will check all files in the directory with txt extension and either write the search string (i.e. "tasks:") if found or else the name of the file.

Share:
126,798

Related videos on Youtube

Chirag Vijay
Author by

Chirag Vijay

Updated on September 18, 2022

Comments

  • Chirag Vijay
    Chirag Vijay over 1 year

    In my bash script I'm trying to print a line if a certain string does not exist in a file.

    if grep -q "$user2" /etc/passwd; then
        echo "User does exist!!"
    

    This is how I wrote it if I wanted the string to exist in the file but how can I change this to make it print "user does not exist" if the user is not found in the /etc/passwd file?

  • Jeff Schaller
    Jeff Schaller about 6 years
    this is really just a longer way of saying what Eric said.
  • ssanch
    ssanch about 6 years
    Well, for me the negative if ! grep ... statement did not work. So this is an alternative.