fork download
  1. awk '
  2. /once was/ { animal = $5 }
  3. /he ate/ { print $4, animal } ' |
  4. sort -u |
  5. awk '
  6. NR == 1 { prev = $1; printf "%s %s", $1, $2 }
  7. NR > 1 { if (prev == $1) { printf " %s", $2 }
  8. else { prev = $1; printf "\n%s %s", $1, $2 } }
  9. END { printf "\n" } ' |
  10. awk '
  11. { if (NR > 1) { print "" }
  12. print "Food:", $1, "Animals who ate it:", NF-1
  13. print "========"
  14. for (N=2; N<=NF; N++) { print $N } } '
Success #stdin #stdout 0s 4700KB
stdin
There once was a Dog

Wednesday he ate Apples 
Thursday he ate Apples
Friday he ate Apples
Saturday he ate carrots

There once was a Bear

Tuesday he ate carrots
Wednesday he ate carrots
Thursday he ate chicken
stdout
Food: Apples Animals who ate it: 1
========
Dog

Food: carrots Animals who ate it: 2
========
Bear
Dog

Food: chicken Animals who ate it: 1
========
Bear