3.4《想成为黑客,不知道这些命令行可不行》(Learn Enough Command Line to Be Dangerous)——grepping(检索目标行命令)

时间:2023-03-09 13:43:34
3.4《想成为黑客,不知道这些命令行可不行》(Learn Enough Command Line to Be Dangerous)——grepping(检索目标行命令)

grep是检查文件内容最强大的工具之一,这也许不能代表什么,但这不是重点。的确,grep常用作动词,比如‘你完全应该检索(grep)那个文件’.

grep最常用于在文件中搜索子字符串。例如,我们在第三章节中学到的在莎士比亚诗中搜索'rose'字符串。而使用grep,我们可以直接找到标记,如Listing 16中展示的那样:

Listing 16: 寻找出现在莎士比亚诗中的'rose'

$ grep rose sonnets.txt

The rose looks fair, but fairer we it deem

As the perfumed tincture of the roses.

Die to themselves. Sweet roses do not so;

Roses of shadow, since his rose is true?

Which, like a canker in the fragrant rose,

Nor praise the deep vermilion in the rose;

The roses fearfully on thorns did stand,

Save thou, my rose, in it thou art my all.

I have seen roses damask'd, red and white,

But no such roses see I in her cheeks;

使用Listing 16中的命令,看来我们得用WC来计数‘rose’个数了(3.3章中介绍过), 正如Listing 17中:

Listing 17:* 对grep的输出结果使用wc*

$ grep rose sonnets.txt | wc

10 82 419

在上面