Reputation: 415
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
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.
Upvotes: 0
Views: 295
Reputation: 204064
It's important to really think about and ask questions if you don't understand a script you're using.
awk 'c&&!--c;/pattern/{c=6}' file
is just using default behavior as shorthand for
awk 'c&&!--c{print $0} /pattern/{c=6}' file
which you can trivially tweak to:
awk 'c&&!--c{print $5} /pattern/{c=6}' file
Upvotes: 0
Reputation: 3783
You can use the built-in NR
variable for this
awk '/pattern/ { nrs[NR + 6] = 1; } NR in nrs { print $5; delete nrs[NR] }'
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.
This solution accounts for the fact that a pattern might occur multiple times within any given 6 line range.
Upvotes: 1