8

I'm currently writing a bash script that should check if the exact string 329, exists in myfile. I have searched through the web and found some answers, but I can't use -x parameters because I have more numbers than 329, on myfile. And without the -x parameter, I can get the Exists result with 329 too, which I don't want.

I tried;

if grep -xqFe "329," "myfile"; then
    echo -e "Exists"
else
    echo -e "Not Exists"
fi

And the output was;

Not Exists

Inside of myfile;

329, 2, 57

How can I solve this?

muru
  • 207,228
Erikli
  • 429

2 Answers2

13

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
wjandrea
  • 14,504
terdon
  • 104,119
-1

Another alternative might be :

if cat myfile | tr "," "\n" | grep -xqF "329"; then
    echo -e "Exists"
else
    echo -e "Not Exists"
fi

Regards

wjandrea
  • 14,504