Bash – Printing a string when grep does not get a match

bashgrep

Suppose I have two files which look as follows:

$ cat search_file.txt
This line contains kwd1.
This line contains kwd2.
This line contains no match.
This line contains no match.
This line contains kwd5.
$ cat search_kwd.sh
grep kwd1 search_file.txt
grep kwd2 search_file.txt
grep kwd3 search_file.txt
grep kwd4 search_file.txt
grep kwd5 search_file.txt

When I run search_kwd.sh, I get:

$ sh search_kwd.sh
This line contains kwd1.
This line contains kwd2.
This line contains kwd5.

I want to print a string whenever grep does not get a match. The output would look like:

$ sh search_kwd.sh
This line contains kwd1.
This line contains kwd2.
string
string
This line contains kwd5.

How do I go about doing this in bash?

Best Answer

grep exits with non-zero code when nothing found.

From man grep:

Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred.

So you can use:

grep kwd3 search_file.txt || echo "string"