function end_of_service() { if (needs_printing!="") { print class; } needs_printing=""; class=""; } BEGIN {FS=": "} { if ($0 ~ /^ [^ ]/) { end_of_service(); } if (index($0, search)) { needs_printing=$0; } if ($1 == " class") { class=$2; } } END { end_of_service(); }