grep -w,只有空格作为定界符

问题描述 投票:3回答:4
grep -w uses punctuations and whitespaces as delimiters. 

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

unix grep word
4个回答
3
投票

如果要匹配just个空格:grep -w foogrep " foo "相同。如果您还想匹配行尾或制表符,则可以开始执行以下操作:grep '\(^\| \)foo\($\| \)',但最好使用perl -ne 'print if /\sfoo\s/'


2
投票

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


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编写扩展的正则表达式,从而使您可以更好地控制搜索模式。


0
投票

使用tr用新行替换空格。然后grep您的字符串。我需要的连续字符串被grep -w分割,因为其中包含冒号。此外,我只知道第一部分,第二部分是我需要提取的未知数据。因此,以下内容对我有所帮助。

echo "$your_content" | tr ' ' '\n' | grep 'string'
© www.soinside.com 2019 - 2024. All rights reserved.