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

标签 linux grep

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

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

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

"grep -nr "a[A-Za-z]*e""

这通过包括像 ape 和 apple 这样的输出来产生答案,但它也包括不需要的 apes。

最佳答案

简单地:

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\>'
      

      在哪里

      The symbols \< and > respectively match the empty string at the beginning and end of a word.

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

关于linux - grep:在目录中查找以特定字母开头和结尾的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47340063/

相关文章:

linux - Azure AKS 添加具有不同 Linux 操作系统的节点

linux - curl, sed//有人知道从网络和进程中提取信息的更好方法吗?

r - "mean"表示值大于 x 的连续行(按组)

linux - 如何在终端中从 grep 中删除列

bash - bash 脚本中的 grep + Jenkins

linux - 如何在 bash 脚本中启动后台 lftp session ?

linux - EPOLLONESHOT 是否阻止在对 epoll_wait() 的单个调用中返回单个描述符上的多个事件?

linux - 如何使用 grep 查找匹配之前 * 和 * 之后的上下文行?

bash - Sed 发现自己并丢弃脚本结果

bash - 如何获取具有特定列值的 csv 文件的前 n 行?