grep -w uses punctuations and whitespaces as delimiters.
如何将grep设置为仅将空白用作单词的分隔符?
如果要匹配just个空格:grep -w foo
与grep " foo "
相同。如果您还想匹配行尾或制表符,则可以开始执行以下操作:grep '\(^\| \)foo\($\| \)'
,但最好使用perl -ne 'print if /\sfoo\s/'
您无法更改grep -w
的工作方式。但是,您可以使用X
或tr
用sed
字符替换标点符号,然后使用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'