This might be a common/easy task but I couldn't figure out from examples on the web or manuals of awk/sed/grep.So, here is the scenario: There is an internal command line tool that prints out a multi-line result for each line in an input file. I have an input file with 500K lines.In the output of the tool, there is always a line which is like src: /some/directoryI want to extract this line if and only if there is the specific string foo in the same output. The number of rows between these lines might be different, so this question is somewhat related but not exactly what I'm trying to do.Match multiple regular expressions from a single file using awk How can I do this using awk, sed or grep? I can do it using Python but I don't want to because I want to learn awk/sed and this might be a good example. Here is what I tried with grep:tool -inputfile | if grep foo; then grep src:  ; fi > result.txtThis doesn't produce the result I expected, probably because of something related to buffering.Trying with awk:tool -inputfile | awk '{for (i=1;i<NF;i++) {if(match($i, foo)) print ??? }}' > result.txtHow do I print the line that contains src:  in this script?Example outputs of the tool:Output 1:src: /usr/bin param1: value1 value2 param2: foo param3: bar spam param4: eggs spam spamOutput 2:src: /dev/nullparam1: value1 value2param2: ham spam eggsSo for these 2 cases, I am trying to extract just the 1st one, ie: src: /usr/bin
Print a line in stdout that matches an expression if the output contains another expression
sed;awk;grep
If you know that src: occurs at the beginning of a line and that foo is enclosed in quotes and preceded by a space and that there must be a colon earlier in the line, useawk 'BEGIN{a=0} /^$/{if(a==1) print b; a=0} /:.* foo/{a=1} /^src:/{b=$0} END{if(a==1) print b}'We use the variable a to remember whether or not the pattern foo occurs in the input block, and the variable b to store the src: line. At the beginning, a is set to 0. Whenever we find an empty line (i.e., ^$), we check the value of a, conditionally print b, and reset a. If we encounter foo preceded by a colon earlier in the line, we set a to 1. If we encounter src: at the beginning of a line (^), we store it in b. At the end, we check once more whether a == 1, if so, we print b.