【问题标题】:using bash to print index of maximum value in array使用 bash 打印数组中最大值的索引
【发布时间】:2019-03-23 07:46:50
【问题描述】:

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

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 行,然后打印数组中最新内核的索引值

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

【问题讨论】:

  • Bash 无法将 4.9.85 与 0 进行比较...看起来您需要的不仅仅是一个简单的循环。
  • 对不起,我刚刚更新了代码,目前我可以得到一个输出,但是在我寻找更大的数字时它会抛出更低的值
  • 如果你想进行版本排序,这就是 GNU sort -V 参数的用途。
  • 顺便说一句,array=( $(...) ) 是一种反模式;见BashPitfalls #50

标签: linux bash


【解决方案1】:

代码中的注释:

# our array
arr=( 
     1.1.1  # first element
     2.2.2 
     4.9.85 # third element, the biggest
     4.9.38 
)

# print each array element on a separate line
printf "%s\n" "${arr[@]}" | 
# substitute the point to a space, so xargs can process it nicely
tr '.' ' ' |
# add additional zeros to handle single digit and double digit kernel versions
xargs -n3 printf "%d%02d%02d\n" |
# add line numbers as the first column
nl -w1 |
# number sort via the second column
sort -k2 -n |
# get the biggest column, the latest
tail -n1 |
# get the first field, the line/index number
cut -f1

它会输出:

3

tutorialspoint 上提供实时代码。

【讨论】:

    【解决方案2】:
    • 如果数字对齐,您可以进行字符串比较。
    • printf 可以对齐数字
    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[@]}")"
    

    【讨论】:

      猜你喜欢
      • 2012-02-17
      • 1970-01-01
      • 2019-10-26
      • 2020-09-19
      • 2019-05-14
      • 2014-06-26
      • 1970-01-01
      • 2022-01-05
      • 2013-01-11
      相关资源
      最近更新 更多