The -x
isn't relevant here. That means (from man grep
):
-x, --line-regexp
Select only those matches that exactly match the whole line.
For a regular expression pattern, this is like parenthesizing
the pattern and then surrounding it with ^ and $.
So it is only useful if you want to find lines that contain nothing other than the exact string you are looking for. The option you want is -w
:
-w, --word-regexp
Select only those lines containing matches that form whole
words. The test is that the matching substring must either be
at the beginning of the line, or preceded by a non-word
constituent character. Similarly, it must be either at the end
of the line or followed by a non-word constituent character.
Word-constituent characters are letters, digits, and the
underscore. This option has no effect if -x is also specified.
That will match if you find your target string as a standalone "word", as a string surrounded by "non-word" characters. You also don't need the -F
here, that is only useful if your pattern contains characters with special meanings in regular expressions which you want to find literally (e.g. *
), and you don't need -e
at all, that would be needed if you wanted to give more than one pattern. So you're looking for:
if grep -wq "329," myfile; then
echo "Exists"
else
echo "Does not exist"
fi
If you also want to match when the number is the last one on the line, so it has no ,
after it, you can use grep -E
to enable extended regular expressions and then match either a 329
followed by a comma (329,
) or a 329
that is at the end of the line (329$
). You can combine those like this:
if grep -Ewq "329(,|$)" myfile; then
echo "Exists"
else
echo "Does not exist"
fi