Display exact matches only with GREP

落爺英雄遲暮 提交于 2019-12-18 15:29:22

问题


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

回答1:


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



回答2:


This may work for you

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



回答3:


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



回答4:


^ 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$'



回答5:


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



回答6:


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

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




回答7:


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




回答8:


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.



来源:https://stackoverflow.com/questions/19576292/display-exact-matches-only-with-grep

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!