我如何在每一条匹配的线周围显示前面和后面的5条线?
当前回答
$ grep thestring thefile -5
-5会让你在匹配项上下各5行,“thestring”相当于-C 5或-A 5-B 5。
其他回答
对于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:
-A 5 # this will give you 5 lines after searched string.
-B 5 # this will give you 5 lines before searched string.
-C 5 # this will give you 5 lines before & after searched string
实例File.txt包含6行,以下是操作。
[abc@xyz]~/% cat file.txt # print all file data
this is first line
this is 2nd line
this is 3rd line
this is 4th line
this is 5th line
this is 6th line
[abc@xyz]~% grep "3rd" file.txt # we are searching for keyword '3rd' in the file
this is 3rd line
[abc@xyz]~% grep -A 2 "3rd" file.txt # print 2 lines after finding the searched string
this is 3rd line
this is 4th line
this is 5th line
[abc@xyz]~% grep -B 2 "3rd" file.txt # Print 2 lines before the search string.
this is first line
this is 2nd line
this is 3rd line
[abc@xyz]~% grep -C 2 "3rd" file.txt # print 2 line before and 2 line after the searched string
this is first line
this is 2nd line
this is 3rd line
this is 4th line
this is 5th line
记住选项的技巧:选项:
-一个 -> 之后的平均值-B级 -> B表示之前。-c类 -> 介于两者之间
如果您经常搜索代码,AG银搜索器比grep更高效(即更快)。
使用-C选项显示上下文行。
Eg:
ag -C 3 "foo" myFile
line 1
line 2
line 3
line that has "foo"
line 5
line 6
line 7
我采用紧凑的方式:
grep -5 string file
这相当于:
grep -A 5 -B 5 string file
grep astring myfile -A 5 -B 5
这将grep“myfile”表示“跨步”,并在每次比赛前后显示5行
推荐文章
- 命令行svn for Windows?
- 为什么logcat没有显示任何东西在我的Android?
- 在Python中记录未捕获的异常
- 重定向复制的标准输出到日志文件从bash脚本本身
- 如何找到最近修改文件的git提交?
- 如何将多行输出连接到一行?
- 使用grep搜索包含点的字符串
- Python日志:使用时间格式的毫秒
- Grep输出只显示匹配的文件
- IE8的console.log怎么了?
- 在命令行中切换php版本
- 如何使Vim不突出显示所搜索的内容?
- 如何从Kubernetes复制控制器的所有pod中获取日志?
- Spring RestTemplate -如何启用请求/响应的完整调试/日志记录?
- 无法像使用CTRL-r一样转发搜索Bash历史