Combine results of column one Then sum column 2 to list total for each entry in column one

前端 未结 3 1081
失恋的感觉
失恋的感觉 2021-01-14 08:13

I am bit of Bash newbie, so please bear with me here.

I have a text file dumped by another software (that I have no control over) listing each user with number of ti

3条回答
  •  星月不相逢
    2021-01-14 08:49

    Pure Bash:

    declare -A result                 # an associative array
    
    while read name value; do
      ((result[$name]+=value))
    done < "$infile"
    
    for name in ${!result[*]}; do
      printf  "%-10s%10d\n"  $name  ${result[$name]}
    done
    

    If the first 'done' has no redirection from an input file this script can be used with a pipe:

    your_program | ./script.sh
    

    and sorting the output

    your_program | ./script.sh | sort
    

    The output:

    Bob              219
    Richard          142
    Jim              245
    Mark             190
    John             208
    Sean             201
    

提交回复
热议问题