Awk/Unix group by

前端 未结 6 1458
鱼传尺愫
鱼传尺愫 2020-12-04 14:17

have this text file:

name, age
joe,42
jim,20
bob,15
mike,24
mike,15
mike,54
bob,21

Trying to get this (count):

joe 1
jim 1
         


        
6条回答
  •  萌比男神i
    2020-12-04 14:59

    $ awk -F, 'NR>1{arr[$1]++}END{for (a in arr) print a, arr[a]}' file.txt
    joe 1
    jim 1
    mike 3
    bob 2
    

    EXPLANATIONS

    • -F, splits on ,
    • NR>1 treat lines after line 1
    • arr[$1]++ increment array arr (split with ,) with first column as key
    • END{} block is executed at the end of processing the file
    • for (a in arr) iterating over arr with a key
    • print a print key , arr[a] array with a key

提交回复
热议问题