Reputation: 21
I am wondering how to use the output from a command as the pattern argument of grep
? In particular, I have this command I've cooked up (with help from another question):
grep PATTERN file.txt | awk 'NR == 1 {line = $0; min = $5} NR > 1 && $5 < min {line = $0; min = $5} END{print $5}'
that will search file.txt for the line whose 5th column has the lowest value, then print that value. However, I want to then redirect that into grep
again, to search file.txt again for that line, so that I may print at least 2 lines above, and 5 lines below (though more isnt' a big deal).
I've looked around, and I know that piping output into grep
means you search that output for the argument you give to grep
- but I am not sure how to do it the other way around?
Any help would be greatly appreciated. Thanks!
Upvotes: 2
Views: 217
Reputation: 41460
Why not do all in one awk
awk '/PATTERN/ && (!min || $5 < min) {min=$5;c=NR} {a[NR]=$0} END{for (i=c-2;i<=c+5;i++) print a[i]}' file
This find the line number where filed 5
has lowest value and store it in c
It also store all lines in array a
with line number as index.
Then in end section it prints out from array a
2 lines before and 5
lines after, including the hit line.
Upvotes: 0
Reputation: 21
Never mind, I figured it out. I can redirect the output to a file, then grep using the -f option to search for the strings in that file. Thanks anyway! Hope this helps if you are reading this with the same problem as me...
Upvotes: 0
Reputation: 75575
If you want to use the output of the command as a command line argment to grep, you can use a subshell with $( ...)
syntax.
grep $(grep PATTERN file.txt | awk 'NR == 1 {line = $0; min = $5} NR > 1 && $5 < min {line = $0; min = $5} END{print $5}') Haystack
To get 2 lines of context above and 5 lines below, you can use the -A
and -B
flags.
grep -B2 -A5 $(grep PATTERN file.txt | awk 'NR == 1 {line = $0; min = $5} NR > 1 && $5 < min {line = $0; min = $5} END{print $5}') Haystack
Upvotes: 1