How to grep for the whole word

前端 未结 5 423
一生所求
一生所求 2020-11-30 02:48

I am using the following command to grep stuff in subdirs

find . | xargs grep -s \'s:text\'

However, this also finds stuff like

相关标签:
5条回答
  • 2020-11-30 03:14

    You can drop the xargs command by making grep search recursively. And you normally don't need the 's' flag. Hence:

    grep -wr 's:text' 
    
    0 讨论(0)
  • 2020-11-30 03:19

    Use \b to match on "word boundaries", which will make your search match on whole words only.

    So your grep would look something like

    grep -r "\bSTRING\b"
    

    adding color and line numbers might help too

    grep --color -rn "\bSTRING\b"
    

    From http://www.regular-expressions.info/wordboundaries.html:

    There are three different positions that qualify as word boundaries:

    • Before the first character in the string, if the first character is a word character.
    • After the last character in the string, if the last character is a word character.
    • Between two characters in the string, where one is a word character and the other is not a word character.
    0 讨论(0)
  • 2020-11-30 03:21

    If you just want to filter out the remainder text part, you can do this.

    xargs grep -s 's:text '

    This should find only s:text instances with a space after the last t. If you need to find s:text instances that only have a name element, either pipe your results to another grep expression, or use regex to filter only the elements you need.

    0 讨论(0)
  • 2020-11-30 03:31

    You want the -w option to specify that it's the end of a word.

    find . | xargs grep -sw 's:text'

    0 讨论(0)
  • 2020-11-30 03:35

    you could try rg, https://github.com/BurntSushi/ripgrep :

    rg -w 's:text' . 
    

    should do it

    0 讨论(0)
提交回复
热议问题