Linux 使用 grep 匹配精确的单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12718457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Match exact word using grep
提问by Sriharsha Kalluru
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
。
采纳答案by stevo81989
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.
这表明任何以单词 test1 作为第一行的内容。现在,如果您需要在行中间完成此操作,这将不起作用,但您对此并不十分具体。至少在给出 ^ 的示例中将起作用。
回答by Matt
For your sample you can specify the beginning of the line with a ^
and the space with \s
in the regular expression
对于您的示例,您可以使用正则表达式中的a^
和空格指定行的开头\s
grep "^test1\s" file
It depends on what other delimiters you might need to match as well.
这取决于您可能还需要匹配哪些其他分隔符。
回答by salim khatib
I know I'm a bitlate but I found this question and thought of answering. A wordis 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. sorry I could find a better way if someone can please correct me :)
这将搜索以 test1 开头的行或以至少一个空格开头的 test 行。对不起,如果有人可以纠正我,我可以找到更好的方法:)
回答by Naga Sai
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