本文介绍了使用bash打印数组中最大值的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在数组中打印最大值的索引值.我写了这样的东西:

I am trying to print index value of maximum value in an array. I wrote something like this:

my_array=( $(cat /etc/grub.conf | grep title | cut -d " " -f 5,7 | tr -d '()'|cut -c1-6) )
echo "${my_array[*]}" | sort -nr | head -n1
max=${my_array[0]}
for v in ${my_array[@]}; do
    if (( $v > $max )); then max=$v; fi;
done
echo $max

此脚本的输出如下:

4.9.85 4.9.38
./grub_update.sh: line 6: ((: 4.9.85 > 0 : syntax error: invalid arithmetic operator (error token is ".9.85 > 0 ")
./grub_update.sh: line 6: ((: 4.9.38 > 0 : syntax error: invalid arithmetic operator (error token is ".9.38 > 0 ")
0

要求:我想查询grub.conf并读取Kenrnel行,然后在数组中打印最新内核的索引值

Requirement: I want to query grub.conf and read Kenrnel line followed by printing index value of latest kernel in the array

kernel /boot/vmlinuz-4.9.38-16.35.amzn1.x86_64 root=LABEL=/ console=tty1 console=ttyS0 selinux=0

推荐答案

  • 如果数字对齐,则可以进行字符串比较.
  • printf 可以对齐数字
    • You can do string comparisons if the digits are aligned.
    • printf can align the digits
    • data=(
          4.9.85
          4.9.38
          3.100.20.2
          4.12.2.4.5
          4.18.3
      )
      
      findmax(){
          local cur
          local best=''
          local ans
      
          for v in "$@"; do
              cur="$(
                  # split on dots
                  IFS=.
                  printf '%04s%04s%04s%04s%04s' $v
              )"
              # note: sort order is locale-dependent
              if [[ $cur > $best ]]; then
                  ans="$v"
                  best="$cur"
              fi
          done
          echo "$ans"
      }
      
      echo "max = $(findmax "${data[@]}")"
      

      这篇关于使用bash打印数组中最大值的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 14:06