1

I have a script that detects crop values before I start video encoding. I do several probes at a certain interval, say every 100th frame. If all the crop values for all the probed frames match then there is no problem and the script kicks in the encoding function. If crop values differ then script exits with an error and I need to pick the correct crop value manually which is annoying.

So, instead of exiting the script with an error I would rather pick the "best" possible value which, in this situation, is the number that repeats the most.

So how do I pick a string out of the collection that repeats the most?

Say, I put all the crop values in an array. Crop=('3' '4' '3' '5' '7' '3' '7'); So in this situation I would pick value '3' as it repeats most often. How can I do it programmatically in Bash?

Thanks.

-- EDIT --

I do apologize, to simplify my question I might have confused some of you. The real crop values look like this "720:568:0:4".

2
  • Both the solutions work for (720:568:0:4 100:200:1:10 720:568:0:4 300:400:100:130) as well. Commented Mar 19, 2013 at 0:39
  • @choroba Indeed. I just tested ... Commented Mar 19, 2013 at 0:46

1 Answer 1

2

Pure bash solution using an associative array (bash version 4 needed):

#! /bin/bash
crop=(3 4 3 5 7 3 7)
declare -A count
max=0
for c in "${crop[@]}" ; do
    (( count[$c]++ ))
    if (( count[$c] > max )) ; then
        max=${count[$c]}
        idx=$c
    fi
done
echo $idx
Sign up to request clarification or add additional context in comments.

3 Comments

Why using both (( )) and let ? Make your choice =) ((count[$c]++))
@sputnick: Sometimes I also use both let and (( )). To me let i++ looks better than (( i++ )). :)
Then you make quoting mistakes, as in this answer by letting through a glob. Better (single quotes): let 'count[$c]++'. (( count[$c]++ )) should really be preferred unless you have a specific reason for using let. It also typically performs better.

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.