我如何在每一条匹配的线周围显示前面和后面的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;
其他回答
如果您经常搜索代码,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
对于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 astring myfile -A 5 -B 5
这将grep“myfile”表示“跨步”,并在每次比赛前后显示5行
-A和-B将起作用,-C n(对于n行上下文)或-n(对于n个上下文……只要n是1到9)也会起作用。
让我们用一个例子来理解。我们可以使用带有选项的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类 -> 介于两者之间
推荐文章
- Python日志记录不输出任何东西
- IE9是否支持console.log,它是一个真实的功能吗?
- 有nginx access_log和error_log日志的STDOUT和STDERR的主进程
- PowerShell等价于grep -f
- 在Python Django中运行单元测试时,如何禁用日志记录?
- 哪里是logging.config.dictConfig的完整示例?
- Log4j日志层次顺序
- 寻找不属于特定用户的文件
- 如何在MySQL中查看日志文件?
- 截断SQL Server日志文件的命令是什么?
- 在pytest测试中记录日志
- 如何在文件中grep不区分大小写的字符串?
- 如何在SQL Server Management Studio中查看查询历史
- ElasticSearch初学者指南
- Python中带有回溯的日志异常