grep -A :显示匹配行和之后的几行
我经常用grep找东西,比如用户名和密码。大部分站点和用户名和密码都是在一样的,方便grep查找。有时,为了文本好看,我会放在多行。比如 wikipedia多个语言版本上有多个账号,就放在wikipedia总栏目下。这时,光 grep wikipedia 密码文件.txt 就不行了。因为实际的用户名和密码在匹配那行的下面呢。
这是 -A 开关就有用了。
grep手册中的解释:
Context Line Control
-A NUM, –after-context=NUM
Print NUM lines of trailing context after matching lines.
Places a line containing a group separator (–) between
contiguous groups of matches. With the -o or –only-matching
option, this has no effect and a warning is given.
-B NUM, –before-context=NUM
Print NUM lines of leading context before matching lines.
Places a line containing a group separator (–) between
contiguous groups of matches. With the -o or –only-matching
option, this has no effect and a warning is given.
-C NUM, -NUM, –context=NUM
Print NUM lines of output context. Places a line containing a
group separator (–) between contiguous groups of matches. With
the -o or –only-matching option, this has no effect and a
warning is given.
grep -A 4 wikipedia 密码文件.txt
简单翻译就是,-A -B -C 后面都跟阿拉伯数字,-A是显示匹配后和它后面的n行。-B是显示匹配行和它前面的n行。-C是匹配行和它前后各n行。总体来说,-C覆盖面最大。用它保险些。哈哈。这3个开关都是关于匹配行的上下文的(context)。
于是,就是搜索密码文件,找到匹配“wikipedia”字串的行,显示该行后后面紧跟的4行。
这种方法比用程序打开该文件搜索关键字要快得多!