我正在自学命令和使用 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'
一些解释
- 因为这个问题被标记为 linux , 这个答案使用
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:]]
a
和e
是字母- 您可能已经知道
*
这意味着 前面的项目将被匹配零次或多次。(在同一手册页的其他地方: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/