3
grep -w uses punctuations and whitespaces as delimiters. 

如何将 grep 设置为仅使用空格作为单词的分隔符?

4

4 回答 4

3

如果您只想匹配空格:grep -w foogrep " foo ". 如果您还想匹配行尾或制表符,您可以开始执行以下操作:grep '\(^\| \)foo\($\| \)',但您可能会更好perl -ne 'print if /\sfoo\s/'

于 2012-06-07T12:27:29.610 回答
2

你无法改变工作方式grep -w。但是,您可以X使用trorsed然后使用替换标点符号grep -w,这样就可以解决问题。

于 2012-06-07T12:10:16.287 回答
2

--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让你更好地控制你的搜索模式。

于 2012-06-07T12:16:18.063 回答
0

用于tr用新行替换空格。然后是grep你的字符串。我需要的连续字符串被分割了,grep -w因为它里面有冒号。而且,我只知道第一部分,第二部分是我需要拉取的未知数据。因此,以下内容帮助了我。

echo "$your_content" | tr ' ' '\n' | grep 'string'
于 2019-11-12T23:01:18.770 回答