grep -w uses punctuations and whitespaces as delimiters.
如何将 grep 设置为仅使用空格作为单词的分隔符?
如果您只想匹配空格:grep -w foo
与grep " foo "
. 如果您还想匹配行尾或制表符,您可以开始执行以下操作:grep '\(^\| \)foo\($\| \)'
,但您可能会更好perl -ne 'print if /\sfoo\s/'
你无法改变工作方式grep -w
。但是,您可以X
使用tr
orsed
然后使用替换标点符号grep -w
,这样就可以解决问题。
--word-regexp 标志很有用,但有限。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
underscore.
如果您想使用自定义字段分隔符,awk 可能更适合您。或者你可以用 egrep 写一个扩展的正则表达式,或者grep --extended-regexp
让你更好地控制你的搜索模式。
用于tr
用新行替换空格。然后是grep
你的字符串。我需要的连续字符串被分割了,grep -w
因为它里面有冒号。而且,我只知道第一部分,第二部分是我需要拉取的未知数据。因此,以下内容帮助了我。
echo "$your_content" | tr ' ' '\n' | grep 'string'