如何使用awk在文件中的模式后打印5个连续行 [英] How to print 5 consecutive lines after a pattern in file using awk
问题描述
我想在文件中搜索一个模式并在找到该模式后打印 5 行.
I would like to search for a pattern in a file and prints 5 lines after finding that pattern.
为了做到这一点,我需要使用 awk
.
I need to use awk
in order to do this.
示例:
文件内容:
.
.
.
.
####PATTERN#######
#Line1
#Line2
#Line3
#Line4
#Line5
.
.
.
如何解析文件并仅打印上述行?我是否使用包含PATTERN"的行的 NR 并继续增加到 5 并在此过程中打印每一行.请让我知道是否有任何其他有效的 wat 可以在 awk 中做到这一点.
How do I parse through a file and print only the above mentioned lines? Do I use the NR of the line which contains "PATTERN" and keep incrementing upto 5 and print each line in the process. Kindly do let me know if there is any other efficient wat to do it in Awk.
推荐答案
另一种在 AWK 中实现的方法:
Another way to do it in AWK:
awk '/PATTERN/ {for(i=1; i<=5; i++) {getline; print}}' inputfile
在sed
中:
sed -n '/PATTERN/{n;p;n;p;n;p;n;p;n;p}' inputfile
在 GNU sed
中:
sed -n '/PATTERN/,+7p' inputfile
或
sed -n '1{x;s/.*/####/;x};/PATTERN/{:a;n;p;x;s/.//;ta;q}' inputfile
#
字符代表一个计数器.使用比要输出的行数少 1 的行数.
The #
characters represent a counter. Use one fewer than the number of lines you want to output.
这篇关于如何使用awk在文件中的模式后打印5个连续行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!