简体   繁体   中英

key value pairs in awk

I have a string of data like

 915 1.1.1.1 Sep 21 06
2478 2.2.2.2 Sep 21 07
1960 2.2.2.2 Sep 21 08
 500 1.1.1.1 Sep 21 09

The desired output is as follows:

1.1.1.1 1415
2.2.2.2 4438

Ie adding up the numbers in the first column. I would like to use awk text processing language to achieve the same. My solution for this was:

echo " 915 1.1.1.1 Sep 21 06
2478 2.2.2.2 Sep 21 07
1960 2.2.2.2 Sep 21 08
 500 1.1.1.1 Sep 21 09"  | awk '{arr[$2]=$1; if($2 in arr ) {val = arr[$2] + $1; arr[$2]=val}} END {for (i in arr) {print i, arr[i]}}'

This does not seem to work. I am not sure what I did wrong.

$ awk '{a[$2]+=$1} END{for(k in a) print k,a[k] | "sort" }' file

1.1.1.1 1415
2.2.2.2 4438

Since you tagged this bash, I'm assuming a native answer is also acceptable. The following can be copied-and-pasted into bash 4.x or newer, and requires no tools external to the shell itself:

s=' 915 1.1.1.1 Sep 21 06
2478 2.2.2.2 Sep 21 07
1960 2.2.2.2 Sep 21 08
 500 1.1.1.1 Sep 21 09'

{
  declare -A data=( )
  while read -r size address _; do
    [[ $address ]] || continue
    (( data[$address]+=size ))
  done

  for k in "${!data[@]}"; do
    v=${data[$k]}
    printf '%s\t%s\n' "$k" "$v"
  done
} <<<"$s"

It works. Keep it simple.

$ echo " 915 1.1.1.1 Sep 21 06
2478 2.2.2.2 Sep 21 07
1960 2.2.2.2 Sep 21 08
 500 1.1.1.1 Sep 21 09" | awk '{ arr[$2] += $1 } END {for (i in arr) { print i, arr[i] } }'

1.1.1.1 1415
2.2.2.2 4438

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM