本文介绍了数组中最常出现的元素(bash 3.2)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用bash的shell脚本中,我想查找数组中数字出现次数最多的情况,并将结果存储在变量$ result中.该数组可以具有任意数量的值.如果返回多个结果,那么我想选择最低的数字.

In a shell script using bash i would like to find the most frequent occurrence of a number within an array and store the result in variable $result. The array could have any number of values. If multiple results are returned then I would like to select the lowest number.

我了解bash可能不是最好的工具,并且我愿意使用Mac OS X系统上脚本中的命令行中提供的工具来提出建议.

I understand bash may not be the best tool for this and I am open to suggestions using tools available from the command line within my script on a Mac OS X system.

示例:

array =(03 03 03 04 04 04 04)
3次出现03
4次出现04
应该将04返回到名为$ result的变量.

array=(03 03 03 04 04 04 04)
3 occurrences of 03
4 occurrences of 04
Should return 04 into a variable named $result.

另一个例子:

array =(03 03 03 03 04 04 04 04 04)
4次出现03
4次出现04
选择最低的数字03
应该将03返回到名为$ result的变量中.

谢谢您的帮助.

array=(03 03 03 03 04 04 04 04)
4 occurrences of 03
4 occurrences of 04
Select lowest number which is 03
Should return 03 into a variable named $result.

Thank you for your help.

推荐答案

这是一个基于awk的解决方案,它避免了bash关联数组:

Here's an awk-based solution that avoids bash-associative arrays:

#!/bin/bash
get_result(){
awk '
  { 
      n=++hsh[$1]
      if(n>max_occ){
         max_occ=n
         what=$1
      }else if(n==max_occ){
         if(what>$1) 
             what=$1
      }
  } 
  END { print what }
'
}

array=(03 03 03 04 04 04 04)
result=$(printf "%s\n" "${array[@]}" |  get_result)
echo $result

array=(03 03 03 03 04 04 04 04)
result=$(printf "%s\n" "${array[@]}" |  get_result)
echo $result

在您的示例中,结果为03和04.

The results are 03 and 04 as in your example.

这篇关于数组中最常出现的元素(bash 3.2)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 11:36