search.awk
BEGIN {
FS = "="
cur_username = ""
}
$1 ~ /User-Name/ {
cur_username = $2
gsub(/^[ \t]+/, "", cur_username)
gsub(/[ \t]+$/, "", cur_username)
}
$1 !~ /User-Name/ {
if ((NF != 2) || (cur_username != searched_user))
next
key = $1
gsub(/^[ \t]+/, "", key)
gsub(/[ \t]+$/, "", key)
value = $2
gsub(/^[ \t]+/, "", value)
gsub(/[ \t]+$/, "", value)
values[key] = values[key] " " value
}
END {
printf("User-Name = %s\n", searched_user)
for(key in values) {
printf("\t%s =%s\n", key, values[key])
}
}
Execução de teste:
$ awk -f search.awk -v 'searched_user="Mark"' input
User-Name = "Mark"
Acct-Status-Type = Interim-Update Interim-Update
Acct-Input-Octets = 95684 95684
Framed-IP-Address = 0.0.0.0 0.0.0.0
Acct-Output-Octets = 23564 23564
Bônus - group.awk
para agrupar todos os registros (muito ruim nawk não tem asorti
):
BEGIN {
FS = "="
cur_username = ""
}
$1 ~ /User-Name/ {
cur_username = $2
gsub(/^[ \t]+/, "", cur_username)
gsub(/[ \t]+$/, "", cur_username)
}
$1 !~ /User-Name/ {
if (NF != 2)
next
key = $1
gsub(/^[ \t]+/, "", key)
gsub(/[ \t]+$/, "", key)
value = $2
gsub(/^[ \t]+/, "", value)
gsub(/[ \t]+$/, "", value)
users[cur_username,key] = users[cur_username,key] " " value
}
END {
n = asorti(users, sorted)
prev_username = ""
for (i=1; i<=n; i++) {
username_key = sorted[i]
split(username_key, a, SUBSEP)
username = a[1]
key = a[2]
value = users[sorted[i]]
if (username != prev_username) {
printf("User-Name = %s\n", username)
prev_username = username
}
printf("\t%s =%s\n", key, value)
}
}
Execução de teste:
$ gawk -f group.awk input
User-Name = "Mark"
Acct-Input-Octets = 95684 95684
...
User-Name = "Mike"
Acct-Input-Octets = 95684 95684
...