Match exact word using grep

2019-05-31 02:25发布

I have a requirement to search for an exact word and print a line. It is working if I don't have any . (dots) in the line.

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

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

It is giving the second line also and I want only the lines with the exact word test1.

标签: linux shell
4条回答
该账号已被封号
2楼-- · 2019-05-31 02:56

For your sample you can specify the beginning of the line with a ^ and the space with \s in the regular expression

grep "^test1\s" file

It depends on what other delimiters you might need to match as well.

查看更多
Emotional °昔
3楼-- · 2019-05-31 03:07

Try this:

grep -E "^test1" file

This states that anything that starts with the word test1 as the first line. Now this does not work if you need to fin this in the middle of line but you werent very specific on this. At least in the example given the ^ will work.

查看更多
我想做一个坏孩纸
4楼-- · 2019-05-31 03:10

You can take below as 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 below regular expression to search a word starting with test1 and a line that has a word test1 in between of line also.

$ grep -E '(^|\s+)test1\b' /tmp/file   
test1 ALL=ALL    
abc test1 ALL=ALL   
  test1 ALL=ALL
查看更多
Deceive 欺骗
5楼-- · 2019-05-31 03:11

I know I'm a bit late but I found this question and thought of answering. A word is defined as a sequence of characters and separated by whitespaces. so I think this will work grep -E ' +test1|^test1' file


this searches for lines which begin with test1 or lines which have test preceded by at least one whitespace. sorry I could find a better way if someone can please correct me :)

查看更多
登录 后发表回答