Maximum element and its indices from an array in shell script

纵然是瞬间 提交于 2020-01-02 07:15:12

问题


How can I find the maximum element and its index from an array in shell script. I have an array

a = [-2.2116565098 -2.1238242060 -2.1747941240 -2.3201010162 -2.3677779871 -1.8126464132 -2.1247209755 -2.1190930712 -2.3242384636 -2.1081702064];

Now, I want to find the maximum as well as its index in bash script. Is there a shortcut like in Matlab we have

[C, I] = max(a);

Also, also how can we have multi-dimensional array and get the index and value of minimum and maximum element.


回答1:


$ x='-2.2116565098 -2.1238242060 -2.1747941240 -2.3201010162 -2.3677779871'
$ IC=(`tr ' ' '\n' <<<$x | cat -n | sort -k2,2nr | head -n1`)
$ I=${IC[0]} C=${IC[1]}
$ echo $I $C
2 -2.1238242060



回答2:


Shell scripts in general do not support arrays at all, so what you are asking for is impossible. I am not aware of any shells that support multi-dimensional arrays, but some shells do provide minimal support for one dimensional arrays. Some of those shells probably provide convenient ways to perform the operations you need. To find the maximum value and the index in bash, which is one particular shell that does provide primitive support for arrays, you will need to loop over the array (as far as I know). However, bash does not provide good support for floating point values, so before you implement this, you should consider using a different language. Here is an example of one method:

idx=0
maxidx=0
max=${a[0]}
for v in ${a[@]}; do
    expr $v \> $max > /dev/null && { maxidx=$idx; max=$v; }
    : $((idx++))
done

There may be better techniques within bash for accessing the array, but it is generally a bad idea IMO to use shell specific constructs. If you are going to be using sh, even arrays really ought to be avoided, because not all shells support them. If you want to use a language feature of a non-standard shell, you might as well use perl, python, ruby, or your language of choice.



来源:https://stackoverflow.com/questions/9566382/maximum-element-and-its-indices-from-an-array-in-shell-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!