4

I have a bash script that pushes different width:height values onto the end of an array. Some of the values are duplicates. What I need to do is loop through the array, count the number of occurrences for each unique value in the array and then retrieve the value with the most duplicates.

dimensions=( )
dimensions[${#dimensions[*]}]="450:180"
dimensions[${#dimensions[*]}]="360:240"
dimensions[${#dimensions[*]}]="360:240"
dimensions[${#dimensions[*]}]="640:480"
dimensions[${#dimensions[*]}]="360:240"
dimensions[${#dimensions[*]}]="640:480"

In the array above I would need to retrieve the value "360:240" since there were 3 duplicates. How can I count the unique values and end up with a variable containing the value with the most duplicates from the array?

mostDuplicates="360:240"
1
  • Can you use bash 4? If so, use an associative array and swap the keys and values. Commented Jan 8, 2013 at 17:48

1 Answer 1

4

Bash version 4 has associative arrays:

#! /bin/bash
dimensions=(
    450:180
    360:240
    360:240
    640:480
    360:240
    640:480)

declare -A count
max=0

for d in ${dimensions[@]} ; do
    if (( ++count[$d] > max )) ; then
        max=${count[$d]}
        winner=$d
    fi
done
echo Winner: $winner, $max times
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.