#!/bin/bash
# Demonstrates how awk can operate stateful across multiple lines
tstfile="$(mktemp)"
exec 3>"$tstfile"
echo Garbage >&3
echo HEADER1 >&3
echo Garbage >&3
echo Garbage >&3
echo Garbage >&3
echo TIMESTAMP1 >&3
echo Garbage >&3
echo Garbage >&3
echo Garbage >&3
echo MATCH1 >&3
echo Garbage >&3
echo HEADER1 >&3
echo Garbage >&3
echo Garbage >&3
echo Garbage >&3
echo TIMESTAMP1 >&3
echo Garbage >&3
echo Garbage >&3
echo Garbage >&3
echo MATCH2 >&3
exec 3>&-
awk '
function clear_state() { header=""; timestamp="" }
BEGIN{ clear_state() }
/^HEADER/{ clear_state(); header=$0 }
header && /^TIMESTAMP/{ timestamp=$0 }
header && timestamp && /^MATCH1/ {
printf("%s @ %s: %s\n", header, timestamp, $0);
clear_state()
}
header && timestamp && /^MATCH2/ {
print($0);
clear_state();
}
' <"$tstfile"
unlink "$tstfile"
Comments