1

I'm quite new to bash and its syntax, therefore I would like to know how to sort a list to get the total number for an inventory of our hard drives.

Example is below. We have many servers and many hard drives from different vendors and models.

How would you count them together based on the numbers and not the occurrence of their name.

ST8000NC0002: 8
ST900MM0168: 1
ST900MM0168: 1
ST9300603SS: 3
ST9300605SS: 4
ST9500620SS: 3
WD1003FBYX: 7
WD1500HLFS: 4
WD9001BKHG: 3
WD9001BKHG: 3
WD9001BKHG: 4
WD9001BKHG: 4

Desired output:

ST8000NC0002: 8 
ST900MM0168: 2 
ST9300603SS: 3 
ST9300605SS: 4 
ST9500620SS: 3 
WD1003FBYX: 7 
WD1500HLFS: 4 
WD9001BKHG: 14
2
  • Thanks jesse_b. Will be more precise in future to avoid misinterpretations.
    – Ves
    Feb 13, 2020 at 14:28
  • 1
    awk '{a[$1]+=$2}END{for(k in a)print k,a[k]}' file | sort
    – user313992
    Feb 13, 2020 at 14:31

2 Answers 2

1

awk is made for this. Populate an array (data) indexed by the first field ($1), accumulating values from the second field ($2). Once the array is populated, output the data using a simple for loop. Pipe the output through sort for convenience.

awk '{data[$1]+=$2} END { for( d in data ) { print d, data[d] } }' input | sort
ST8000NC0002: 8
ST900MM0168: 2
ST9300603SS: 3
ST9300605SS: 4
ST9500620SS: 3
WD1003FBYX: 7
WD1500HLFS: 4
WD9001BKHG: 14
2
  • 1
    Thank you very much. Sorry for the delayed answer. I've tested your solution and tried to understand it on other examples, took a time to figure out how awk works but i think it helped me to get a better understanding of how to handle my inventory. It works like intended. Thanks!
    – Ves
    Feb 28, 2020 at 8:51
  • Glad to have helped!
    – DopeGhoti
    Mar 2, 2020 at 21:42
0

Using GNU datamash:

datamash -W -g 1 sum 2 < file
  • -W use whitspace (spaces/tabs) as field delimiter (instead of tabs)
  • -g 1 group on the first field
  • sum 2 sum values on the second field (per group)

Output:

ST8000NC0002:   8
ST900MM0168:    2
ST9300603SS:    3
ST9300605SS:    4
ST9500620SS:    3
WD1003FBYX:     7
WD1500HLFS:     4
WD9001BKHG:     14

This works fine since your input is already sorted on the first field. For unsorted input, add option -s to sort the input before grouping.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .