grep:find一个以目录中的特定字母开头和结尾的string

我正在教自己的命令和不同的方式来使用grep。 我知道如何在一个目录及其子目录中search一个string,但是在searchstring中的分割时我感到困惑。

例如:我如何search所有以a开头并以e结尾的单词(string大小变化)。 所以我可以在文本文件中find猿或苹果?

编辑更新:我不知道我正在使用的grep版本,但我试过使用:

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

这通过包括像猿和苹果这样的输出来产生答案,但是它也包含了不需要的猿。

只是:

grep '\ba\w*e\b' 

要么

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

要么

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

一些解释

  • 由于这个问题被标记为linux ,这个答案使用GNU grepgrep (GNU grep) 2.27
  • 命令man grep | grep -3 '\\b'的结果 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\>' 

      哪里

      符号\ <和>分别匹配单词开头和结尾的空字符串。

      这可能具有几乎相同的效果 ,但描述严格对应于这个标题: grep:找到一个字符串开始和结束在目录中的特定字母

我想你可以使用:

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

这应该在当前目录中递归地捕获任何.txt文件,并且grep“a …任何字符… e”

[A-Za-z]搜索任何一种情况的字符,“ \+表示“任意数字”。

我想这就是你以后的事情?

编辑:

字界:

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

正如在各种评论中提到的那样,可以使用POSIX标准的grep -E来做到这一点,但这并不是那么符合方便。

我使用了一个脚本文件grep-ape.sh其中包含:

 grep -E -e '(^|[^[:alpha:]])a[[:alpha:]]+e($|[^[:alpha:]])' "$@" 

-E启用扩展的正则表达式。 -e是可选的,但允许我在正则表达式之后添加额外的选项作为“文件名”。 正则表达式查找“​​起始行”或非字母字符,后跟一个或多个附加的字母字符, 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. 

我可以运行grep-ape.sh -n data (展示-e选项的用处,尽管GNU系统会排列选项,所以你不一定会发现问题),并得到:

 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. 

使用非POSIX选项-o (由GNU和BSD版本的grep )只打印匹配的内容,我可以得到输出:

 $ grep-ape.sh -n -o data 1: ate 2:ape 3: ape 4: ape 5: apple 10: ate $ 

这表明,正则表达式正在提取可接受的词语,即使是在没有可接受的词语的情况下也有不可接受的词汇的话。