homer512 icon

stateful awk

homer512 | PRO | 03/23/15 05:25:17 PM UTC | 0 ⭐ | 831 👁️ | Never ⏰ | []
Bash |

870 B

|

None

|

0 👍

/

0 👎

#!/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