Shell脚本中数组中的最大元素及其索引 [英] Maximum element and its indices from an array in shell script

查看:399
本文介绍了Shell脚本中数组中的最大元素及其索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Shell脚本中从数组中找到最大元素及其索引。我有一个数组

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];

现在,我想在bash脚本中找到最大值及其索引。是否有类似Matlab的快捷方式

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.

推荐答案

$ 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

这篇关于Shell脚本中数组中的最大元素及其索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆