我如何在每一条匹配的线周围显示前面和后面的5条线?
当前回答
使用grep
$ grep --help | grep -i context
Context control:
-B, --before-context=NUM print NUM lines of leading context
-A, --after-context=NUM print NUM lines of trailing context
-C, --context=NUM print NUM lines of output context
-NUM same as --context=NUM
其他回答
这是awk中的@Ygor解决方案
awk 'c-->0;$0~s{if(b)for(c=b+1;c>1;c--)print r[(NR-c+1)%b];print;c=a}b{r[NR%b]=$0}' b=3 a=3 s="pattern" myfile
注意:用前后的行数替换a和b变量。
它对于不支持grep的-A、-B和-C参数的系统特别有用。
对于BSD或GNUgrep,可以使用-B num设置匹配前的行数,使用-A num设置匹配后的行数。
grep -B 3 -A 2 foo README.txt
如果希望前后行数相同,可以使用-C num。
grep -C 3 foo README.txt
这将显示前3行和后3行。
使用grep
$ grep --help | grep -i context
Context control:
-B, --before-context=NUM print NUM lines of leading context
-A, --after-context=NUM print NUM lines of trailing context
-C, --context=NUM print NUM lines of output context
-NUM same as --context=NUM
$ grep thestring thefile -5
-5会让你在匹配项上下各5行,“thestring”相当于-C 5或-A 5-B 5。
在/some/file.txt中搜索“17655”,显示前后10行上下文(使用Awk),输出前有行号,后有冒号。当grep不支持-[ACB]选项时,在Solaris上使用此选项。
awk '
/17655/ {
for (i = (b + 1) % 10; i != b; i = (i + 1) % 10) {
print before[i]
}
print (NR ":" ($0))
a = 10
}
a-- > 0 {
print (NR ":" ($0))
}
{
before[b] = (NR ":" ($0))
b = (b + 1) % 10
}' /some/file.txt;
推荐文章
- 如何在文件中grep不区分大小写的字符串?
- 如何在SQL Server Management Studio中查看查询历史
- ElasticSearch初学者指南
- Python中带有回溯的日志异常
- 如何做一个非贪婪匹配在grep?
- 使用grep删除空行
- 将Chrome中的console.log保存为文件
- Git在终端提交时打开VIM,但无法返回终端
- Windows递归grep命令行
- 我怎么能得到'查找'忽略。svn目录?
- Linux相当于Mac OS X的“open”命令
- 在log4j中,在记录日志之前检查isDebugEnabled是否能提高性能?
- 将Node.js配置为记录到文件而不是控制台
- 命令行svn for Windows?
- 为什么logcat没有显示任何东西在我的Android?