[unix] Display exact matches only with grep

How can I display all jobs that ended OK only?

When I try the command below, it shows both OK and NOTOK since both have "OK"

ctmpsm -listall application | grep OK

This question is related to unix control-m

The answer is


try this:

grep -P '^(tomcat!?)' tst1.txt

It will search for specific word in txt file. Here we are trying to search word tomcat


^ marks the beginning of the line and $ marks the end of the line. This will return exact matches of "OK" only:

(This also works with double quotes if that's your preference.)

grep '^OK$'

If there are other characters before the OK / NOTOK (like the job name), you can exclude the "NOT" prefix by allowing any characters .* and then excluding "NOT" [^NOT] just before the "OK":

grep '^.*[^NOT]OK$'

This may work for you

grep -E '(^|\s)OK($|\s)'

This worked for me:

grep  "\bsearch_word\b"  text_file > output.txt  ## \b indicates boundaries. This is much faster.

or,

grep -w "search_word" text_file > output.txt

You need a more specific expression. Try grep " OK$" or grep "[0-9]* OK". You want to choose a pattern that matches what you want, but won't match what you don't want. That pattern will depend upon what your whole file contents might look like.

You can also do: grep -w "OK" which will only match a whole word "OK", such as "1 OK" but won't match "1OK" or "OKFINE".

$ cat test.txt | grep -w "OK"
1 OK
2 OK
4 OK

Try the below command, because it works perfectly:

grep -ow "yourstring"

crosscheck:-

Remove the instance of word from file, then re-execute this command and it should display empty result.


Recently I came across an issue in grep. I was trying to match the pattern x.y.z and grep returned x.y-z.Using some regular expression we may can overcome this, but with grep whole word matching did not help. Since the script I was writing is a generic one, I cannot restrict search for a specific way as in like x.y.z or x.y-z ..

Quick way I figured is to run a grep and then a condition check var="x.y.z" var1=grep -o x.y.z file.txt if [ $var1 == $var ] echo "Pattern match exact" else echo "Pattern does not match exact" fi

https://linuxacatalyst.blogspot.com/2019/12/grep-pattern-matching-issues.html


Try this:

Alex Misuno@hp4530s ~
$ cat test.txt
1 OK
2 OK
3 NOTOK
4 OK
5 NOTOK
Alex Misuno@hp4530s ~
$ cat test.txt | grep ".* OK$"
1 OK
2 OK
4 OK