From 34902049cf496f5b13bad10396248ec8d8780aeb Mon Sep 17 00:00:00 2001 From: Johannes Stoelp Date: Fri, 23 Sep 2022 19:59:30 +0200 Subject: awk: add example to capture values in arrays --- src/tools/awk.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/tools/awk.md b/src/tools/awk.md index 9ea4fc5..7ffe9a8 100644 --- a/src/tools/awk.md +++ b/src/tools/awk.md @@ -126,6 +126,23 @@ done | sort -k2 -n We capture values from `VmRSS` and `Name` into variables and print them at the `END` once processing all records is done. +### Capture in array +```bash +echo 'a 10 +b 2 +b 4 +a 1' | awk '{ + vals[$1] += $2 + cnts[$1] += 1 +} +END { + for (v in vals) + printf "%s %d\n", v, vals[v] / cnts [v] +}' +``` +Capture keys and values from different columns and some up the values. +At the `END` we compute the average of each key. + ### Run shell command and capture output ```bash cat /proc/1/status | awk ' -- cgit v1.2.3