我正在尝试在数组中打印最大值的索引值。我写了这样的东西:
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
答案 0 :(得分:0)
代码注释:
# 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上获得实时代码。
答案 1 :(得分:0)
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[@]}")"