Saturday, May 4, 2024
11
rated 0 times [  11] [ 0]  / answers: 1 / hits: 9991  / 1 Year ago, fri, march 24, 2023, 7:43:04

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?


More From » command-line

 Answers
4

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

[#322] Sunday, March 26, 2023, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
diffeah

Total Points: 78
Total Questions: 130
Total Answers: 98

Location: Peru
Member since Fri, Oct 14, 2022
2 Years ago
;