在linux和unix系统里编写shell时经常会用到grep命令,笔者在编写一个shell遇到一个很困惑的问题,就是如何用grep命令更直接的提取到我们想要的信息,并剔除我们不需要的信息,比如我想找到一个文件里含有字符串host的一行文件内容,但是我不想获得含有sendhost的一行文件内容。

笔者在网上找了很久找到一天关于grep -w的应用,原来的例子我找不到了,但是我在一个linux系统下用man grep命令获取下列的信息

……

-w, --word-regexp
              Select  only  those  lines  containing matches that form whole words.  The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character.   Similarly,  it  must  be either  at  the  end  of the line or followed by a non-word constituent character.  Word-constituent characters are  letters, digits, and the underscor

……

这段信息就解释了grep -w的用法,在下英语翻译能力很有限,我就不去翻译上面的内容了,我把我理解的意思举例给大家说一下

比如有一个文档ex.txt内容为:

a bc
bc d
bcd
abc
a bc de

我想获取只含有bc字符串的行,不获取含有bcd或者abc的行,如果我们用grep bc ex.txt,那么获取的内容就是

a bc
bc d
bcd
abc
a bc de

如果我们用命令grep -w bc ex.txt,那运行的结果打印出来就是:

a bc
bc d
a bc de

这就是我们想要的结果。