Come on, don't give up on awk
so fast !
awk 'NR == FNR {
aMatch[NR]=$0
n=FNR
next;
}
{
RS="\n( |\t)*\n"
for(i=1; i<n+1; i++) {
if($0 ~ aMatch[i]) {
print
printf "\n"
break
}
}
}' matchFile myFile | head -n-1
You might want to put that into a script though :
awk -f myscript.awk matchFile myFile | head -n-1
The solution in awk
script form, with annotations on what it does:
# This block's instructions will only be executed for the first file (containing the lines to be matched)
# NR = number of line read, and FNR = number of line read in current file
# So the predicate NR == FNR is only true when reading the first file !
NR == FNR {
aMatch[NR]=$0 # Store the line to match in an array
n=FNR # Store the number of matches
next; # Tells awk to skip further instructions (they are intended for the other file) and process the next record
}
# We are now processing the second file (containing the paragraphs)
{
RS="\n( |\t)*\n" # Set record separator to a blank line. Instead of a single line, a record is now the entire paragraph
for(i=1; i<n+1; i++) { # Loop on all possible matches
if($0 ~ aMatch[i]) { # If $0 (the whole record i.e. paragraph) matches a line we read in file 1 then
print # Print the record (i.e. current paragraph)
printf "\n" # Print a new line to separate them. However we will end up with a trailing newline, hence the pipe to head -n-1 to get rid of it.
break # We need to break out of the loop otherwise paragraphs with n matches will be printed n times
} # End of loop on matches
} # End of 2nd file processing
}