barp
barp

Reputation: 6939

sorting array in bash and regex

I have an array that have the CPU core num and a number for each core. the array is totals.

How can I sort

totals=( CPU0=12345 CPU1=23456 CPU3=01234) 

according to numbers and return the sorted version of cpu number for example (3,0,1) means it is sorted and core 3 is the min and core 1 is the max, in bash? and then assign (3,0,1) to an array?

Upvotes: 0

Views: 338

Answers (1)

Costi Ciudatu
Costi Ciudatu

Reputation: 38235

Try this for sorting:

echo ${totals[*]} | tr ' ' '\n' | sort -n -t= -k2

To store only the CPU numbers in a new array, try:

sorted_cpu_numbers=( $(echo ${totals[*]} | tr ' ' '\n' | sort -n -t= -k2 | awk -F= '{print substr($1, 4, length($1))}') )

Upvotes: 1

Related Questions