grep 命令简介

grep 命令格式

1
grep [options]... "PATTERN" [FILE]...

注意 pattern 部分的正则表达式最好用引号包裹。

实验准备

首先,在当前目录下放置了一个poem文件,作为实验材料。

1
2
3
4
5
6
7
8
9
10
Finding answers
All our days are filled with searching
wondering what we're looking for
All our days are filled with searching
that makes the searching more productive
finding meaning, finding comfort,
finding someone to adore
Can we find a way to be

举个例子

当你知道你要找什么,grep 就是你的朋友,这不只是在你查找特定文本的时候。grep 命令可以帮助你找到任意文本,特定单词,文本模式和有上下文的文本。当你知道文本长什么样时,查找它通常很简单。grep this that 命令会显示“that”文件中包含“this”字符串的每一行。增加 -w 选项就只会显示那些单独包含“this”这个单词的行。换句话说,如果行中包含“thistle” 或 “erethism” 就不会显出来,除非这些行也有 “this” 这个单词。

最简单的 grep 命令不费什么力气就能理解
找到 poem 文件中所有包含 find 的行,并高亮find

1
grep "find" poem

结果为

1
2
3
4
➜ ~ grep "find" poem
finding meaning, finding comfort,
finding someone to adore
Can we find a way to be

查找整个单词可以通过增加 -w 选项完成

1
2
➜ ~ grep -w "find" poem
Can we find a way to be

查找模式 需要一点技巧。我们的第一个例子中显示了包含“find”单词的行,无论“find”中的“f”是大写还是小写:

1
2
3
4
5
➜ ~ grep "[Ff]ind" poem
Finding answers
finding meaning, finding comfort,
finding someone to adore
Can we find a way to be

如果你想匹配以文本起始或结束的行,你可以使用 ^(起始)或 $(结尾)。

1
2
3
➜ ~ grep "^find" poem
finding meaning, finding comfort,
finding someone to adore

如果你想找到包含两个连续元音音节的单词的行,你可以使用如下所示的“AEIOUaeiou”字符。
head -3 表示只显示前三行

1
2
3
4
➜ ~ grep -E "[AEIOUaeiou]{2}" poem | head -3
All our days are filled with searching
wondering what we're looking for
All our days are filled with searching

查找包含 9 个或者 10 个字母的字符串:

1
2
3
4
5
➜ ~ grep -E "[[:alpha:]]{9,10}" poem
All our days are filled with searching
wondering what we're looking for
All our days are filled with searching
that makes the searching more productive

查找一个包含 “find” 的长单词:

1
2
3
➜ ~ grep -E "find[^[:space:]]+" poem
finding meaning, finding comfort,
finding someone to adore

pattern中可以使用转移符号

例如

1
2
3
4
5
6
tar --usage | grep "\-\-f"
[--xattrs-exclude=MASK] [--xattrs-include=MASK] [--file=ARCHIVE]
[--force-local] [--info-script=名称] [--new-volume-script=名称]
[--record-size=NUMBER] [--format=FORMAT] [--old-archive]
[--suffix=STRING] [--files-from=FILE] [--unquote]
[--checkpoint-action=ACTION] [--full-time] [--index-file=FILE]

参考资料

[1] 在 Unix 系统上查找数据的最佳工具和技巧
[2] The best tools and techniques for finding data on Unix systems