grep:查找以目录中的特定字母开头和结尾的字符串

时间:2017-11-16 22:19:44

标签: linux grep

我正在教自己命令和使用grep的不同方法。我知道如何在目录及其子目录中搜索字符串,但在搜索字符串中的分割时我很困惑。

例如:我如何搜索以a开头并以e结尾的所有单词(字符串大小各不相同)。这样我就可以在文本文件中找到猿或苹果?

编辑更新: 我不确定我使用的grep版本,但我尝试使用:

“grep -nr”a [A-Za-z] * e“”

这会产生答案,包括猿和苹果等输出,但它也包括不需要的猿。

3 个答案:

答案 0 :(得分:1)

简单地:

grep '\ba\w*e\b' 

grep --color '\ba\w*e\b'

grep -rn '\ba\w*e\b'

一些解释

  • 由于此问题已标记为,此答案使用 GNU grep grep (GNU grep) 2.27
  • 命令man grep | grep -3 '\\b'的结果:

    The Backslash Character and Special Expressions
        The  symbols  \<  and  \>  respectively  match  the empty string at the
        beginning and end of a word.  The symbol \b matches the empty string at
        the  edge  of a word, and \B matches the empty string provided it's not
        at the edge of a word.  The symbol \w is a synonym for [_[:alnum:]] and
        \W is a synonym for [^_[:alnum:]].
    

    让你展示

    • \b表示单词的边缘
    • \w表示[_[:alnum:]]
    • ae是字母
    • 您可能已经知道*意味着前面的项目将匹配零次或多次。(同一手册页的其他位置:man grep | grep '^ *\*';)
    • ......最后......这可以写成:

      grep '\<a\w*e\>'
      

      ,其中

        

      符号\&lt;和&gt;分别匹配单词开头和结尾的空字符串。

      这可能具有相同的效果,但描述严格对应于此标题: grep:查找以目录中的特定字母开头和结尾的字符串

答案 1 :(得分:0)

我想你可以使用:

find . -type f -name '*.txt' -exec cat {} \; | grep 'a[A-Za-z]\+e'

那应该在当前目录中以递归方式捕获任何.txt文件,然后grep为&#34; a ...任何字符...... e&#34;

[A-Za-z]搜索两种情况的字符,\+说&#34;任意数量的字符&#34;。

我认为那是你之后的事情?

编辑:

字边界:

find . -type f -name '*.txt' -exec cat {} \+ | grep '\ba[A-Za-z]\+e\b'

答案 2 :(得分:0)

正如在各种评论中提到的那样,可以使用POSIX标准grep -E来实现这一点,但它并非完全符合标准。

我使用了包含以下内容的脚本文件"2017-11-17T18:00:00.000 AEDT"

grep-ape.sh

grep -E -e '(^|[^[:alpha:]])a[[:alpha:]]+e($|[^[:alpha:]])' "$@" 启用扩展正则表达式。 -E是可选的,但允许我在正则表达式后面添加额外选项作为“文件名”。正则表达式查找“​​行首”或非字母字符,后跟-e,一个或多个其他字母字符,a和“行尾”或非字母字符。

给定数据文件(称为“{1}}”):

e

我可以运行data(展示I want to tape the apes that ate the grapes. ape at the start. Ending with ape Situating ape in the middle And an apple too. But not apples, no way. The tape ran out. The apes ran out. The grapes ran out. They ate them. 选项的用处,尽管GNU系统会置换选项,因此您不一定会发现问题),并得到:

grep-ape.sh -n data

使用非POSIX选项-e(由GNU和BSD版本的1:I want to tape the apes that ate the grapes. 2:ape at the start. 3:Ending with ape 4:Situating ape in the middle 5:And an apple too. 10:They ate them. 支持)仅打印匹配的内容,我可以得到输出:

-o

这表明正则表达式正在拾取可接受的单词,即使在没有可接受单词的公司中存在不可接受的单词的行上也是如此。