查找以一个特定字符开头并以另一个特定字符结尾的行

Find lines starting with one specific character and ending with another one

我需要在文件中找到以 a 开头且最后一个单词以 e 结尾的行.

如何使用 grep 之类的工具来完成?

就这么说吧:

grep '^a.*e$' file

这意味着:查找那些以 a 开头 (^) 的行,然后是 0 个或多个字符,最后是行尾的 e ($).

测试

$ cat a
hello
and thisfinishes with e
foo
$ grep '^a.*e$' a
and thisfinishes with e

简单的答案:使用 grep。

grep -E "^a.*e$" filename

^表示行首 $ 标记行尾 .* 表示从零到任意次数(*)重复的任何字符(.)。 许多主题已经回答了这个问题,例如 this one。 如果您想了解更多关于搜索的信息,可以更深入地了解 REGEX.

$ grep -E '.*sam.*t' filename

此处 .* 用于正则表达式可以找到的任何字符。 这里的“sam”是我的例子。