Exact match words using grep

I have a requirement to search for the exact word and print the string. It works if I don't have a row . (dots) per line.

 $cat file test1 ALL=ALL w.test1 ALL=ALL $grep -w test1 file test1 ALL=ALL w.test1 ALL=ALL 

It also gives a second line, and I only need lines with the exact word test1 .

+1
source share
4 answers

Try the following:

 grep -E "^test1" file 

This means that everything that starts with the word test1 as the first line. Now this will not work if you need to plan it in the middle of the line, but you are not very accurate about it. At least in the above example ^ will work.

+5
source

In your example, you can specify the beginning of a line with ^ and a space with \s in the regular expression

 grep "^test1\s" file 

It depends on what other separators you might need.

+3
source

I know that I'm a little but I found this question and thought about how to answer. A word is defined as a sequence of characters and is separated by spaces. so I think this will work grep -E '+ test1 | ^ test1 'file


it looks for lines that start with test1 or lines that have a test that is preceded by at least one space. sorry i could find a better way if someone can fix me :)

0
source

You can take below as a sample test file.

 $cat /tmp/file test1 ALL=ALL abc test1 ALL=ALL test1 ALL=ALL w.test1 ALL=ALL testing w.test1 ALL=ALL 

Run under the regex to find the word starting with test1 and the line that also has the word test1 in it.

 $ grep -E '(^|\s+)test1\b' /tmp/file test1 ALL=ALL abc test1 ALL=ALL test1 ALL=ALL 
0
source

Source: https://habr.com/ru/post/1416186/


All Articles