如果使用awk在文件中找到匹配项,则在匹配后打印第"n"行的第"m"列 [英] print "m"th column of "n"th line after a match if found in a file using awk
问题描述
在文件中找到特定的图案后,我需要打印第六行.在第6行中,我只想打印第5列.我可以使用以下命令来解决此问题的第一部分,
I need to print 6th line after a particular pattern is found in a file. In that 6th line, I want to print only the 5th column. I can do the first part of this problem using the following command,
awk 'c&&!--c;/pattern/{c=6}' file
但是我找不到一种方法来修改它以仅打印此第6行的第5列.任何帮助将不胜感激.
but I can't find a way to modify it to print just the 5th column of this 6th line instead. Any help will be greatly appreciated.
推荐答案
You can use the built-in NR
variable for this
awk '/pattern/ { nrs[NR + 6] = 1; } NR in nrs { print $5; delete nrs[NR] }'
这将测试pattern
,并在其行号加六个(NR + 6
)的数组中进行输入.然后,我们对该数组进行简单查找,以查看当前行号是否是我们要打印的行号(nrs[NR] == 1
),然后打印第5列(print $5
),然后清理该数组.
This will test for pattern
and make an entry in an array of the it's line number plus six (NR + 6
). We then do a simple lookup on that array to see if our current line-number is one we want to print (nrs[NR] == 1
) and then print the 5th column (print $5
) and then clean up the array.
此解决方案考虑了以下事实:在给定的6行范围内,模式可能会多次出现.
This solution accounts for the fact that a pattern might occur multiple times within any given 6 line range.
这篇关于如果使用awk在文件中找到匹配项,则在匹配后打印第"n"行的第"m"列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!