自定义排序bash数组 [英] custom sort bash array

查看:46
本文介绍了自定义排序bash数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


res[0]="b 9"
res[1]="a 1"
res[2]="c 10"
printf -- '%s\n' "${res[@]}"

我想对它进行排序,并按bash中的数字顺序显示数组.

I want to sort it and display the array by the order of the number in bash.


a 1
b 9
c 10

这可能吗?

推荐答案

sort 排序:

res[0]="b 9"
res[1]="x 1"
res[2]="c 10"
printf -- '%s\n' "${res[@]}" | sort -k2 -n

输出:


x 1
b 9
c 10


不带 sort 的数字排序:

res[0]="b 9"
res[1]="x 1"
res[2]="c 10"
new=()                             # declare array new

# copy array res to new and use second column as index
for ((i=0;i<${#res[@]};i++)); do
  new[${res[$i]#* }]=${res[$i]% *}
done

# print array new and use its index: ${!new[@]}
for i in "${!new[@]}"; do
  echo "${new[$i]} $i"
done

输出:


x 1
b 9
c 10

这篇关于自定义排序bash数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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