简体   繁体   English

使用grep匹配确切的单词

[英]Match exact word using grep

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 . 它也给出了第二行,我只想要带有单词test1

Try this: 尝试这个:

grep -E "^test1" file

This states that anything that starts with the word test1 as the first line. 这说明以单词test1作为第一行的任何内容。 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. 至少在给出^的示例中有效。

For your sample you can specify the beginning of the line with a ^ and the space with \\s in the regular expression 对于您的示例,可以在正则表达式中用^指定行的开头,并用\\s指定空格\\s

grep "^test1\s" file

It depends on what other delimiters you might need to match as well. 这取决于您还需要匹配哪些其他定界符。

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 所以我认为这可以工作grep -E'+ test1 | ^ test1'文件


this searches for lines which begin with test1 or lines which have test preceded by at least one whitespace. 这将搜索以test1开头的行或以test开头至少一个空格的行。 sorry I could find a better way if someone can please correct me :) 对不起,如果有人可以纠正我,我可以找到更好的方法:)

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. 在正则表达式下运行,以搜索以test1开头的单词以及在行之间也包含单词test1的行。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM