如何使用 awk 在文件中的模式后打印 5 个连续行
我想在文件中搜索模式并在找到该模式后打印 5 行。
我需要使用 awk 才能执行此操作。
示例:
文件内容:
.
.
.
.
####PATTERN#######
#Line1
#Line2
#Line3
#Line4
#Line5
.
.
.
如何解析文件并仅打印上述行? 我是否使用包含“PATTERN”的行的 NR 并保持递增到 5 并打印过程中的每一行。 请让我知道是否有其他有效的方法可以在 Awk 中完成此操作。
I would like to search for a pattern in a file and prints 5 lines after finding that pattern.
I need to use awk
in order to do this.
Example:
File Contents:
.
.
.
.
####PATTERN#######
#Line1
#Line2
#Line3
#Line4
#Line5
.
.
.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
在 AWK 中执行此操作的另一种方法:
在
sed
中:在 GNU
sed
中:或
#
字符代表计数器。使用比要输出的行数少一行的行。Another way to do it in AWK:
in
sed
:in GNU
sed
:or
The
#
characters represent a counter. Use one fewer than the number of lines you want to output.这产生:
This yields:
如果决定给 grep 一个机会,
grep "PATTERN" search-file -A 5
将为您完成这项工作。编辑:您也可以从
awk
脚本内部使用system()
函数调用 grep。grep "PATTERN" search-file -A 5
will do the job for you if decide to give grep a chance.Edit: You can call grep using
system()
function from inside yourawk
script as well.awk
来救援!打印图案行(共 6 行)
跳过图案并打印接下来的五行
awk
to the rescue!to print with the pattern line (total 6 lines)
to skip pattern and print the next five lines
编辑:没有注意到
PATTERN
不应该是输出的一部分。或者
我能想到的最短的是:
读为a趋于0。/qmaild/将a设置为5:-)
Edit: didn't notice
PATTERN
shouldn't be part of the output.or
The shortest I can come up with is:
Read as a tends to 0. /qmaild/ sets a to 5 :-)
快速而肮脏的解决方案:awk '/PATTERN/ {i=0} { if (i<=5) {print $0}; i+=1} 开始 {i=6}'
Quick&dirty solution:
awk '/PATTERN/ {i=0} { if (i<=5) {print $0}; i+=1} BEGIN {i=6}'
与 Johnsyweb 的解决方案一样有限,但使用不同的方法和 GNU
awk
的高级功能,允许完整的 RegEx 记录分隔符,从而产生一段代码,恕我直言,非常awk
- ish:因此,如果您想要一个稳定且可读的解决方案,请遵循 Dennis Williamson 的答案(+1),但也许您在查看这样的行时也只是享受
awk
的美丽。As limited as Johnsyweb's solution but using a different approach and GNU
awk
's advanced feature allowing full RegEx record separators resulting in a piece of code that, IMHO, is veryawk
-ish:So if you want a stable solution that is also readable, go along with Dennis Williamson's answer (+1 for that one) but maybe you too simply enjoy the beauty of
awk
when looking at lines like this.