[英]How to sort an array of strings using substring with Bash
I am writing my first unix bash script and I find it really difficult because I've never used linux before. 我正在写我的第一个unix bash脚本,但是我发现这真的很困难,因为我以前从未使用过Linux。 It is homework from university. 是大学的功课。 I tried a lot of stuff and I've been looking for hours but I simply can't find the right solution. 我尝试了很多东西,我一直在找几个小时,但我根本找不到合适的解决方案。 Can someone give me some directions of what to use to sort strings from array which look like this: 有人可以给我一些如何使用数组对字符串进行排序的指示,如下所示:
room_100056.dat 4
room_8973.dat 2
room_7764.dat 1
room_2092.dat 20
to this: 对此:
room_7764.dat 1
room_8973.dat 2
room_10056.dat 4
room_2092.dat 20
When sorting the initial array, I am creating a new array which contains the sorted data. 在对初始数组进行排序时,我正在创建一个包含已排序数据的新数组。 The problem is that in the sorted array, the data is printed like this: 问题是在排序数组中,数据的打印方式如下:
room_100056.dat
room_8973.dat
room_7764.dat
room_2092.dat
1
2
4
20
Code: 码:
file=$1/*.dat
count_visits=()
for room in $file
do
visits=$(grep "<Visit>" $room | wc -l)
filename=$(basename $room)
count_visits+=($filename$'\t'$visits)
done
sorted_visits=($(echo ${count_visits[@]} | tr " " "\n" | sort -g))
printf '%s\n' "${sorted_visits[@]}"
exit
告诉sort
在数字上使用第二列:
printf '%s\n' "${count_visits[@]}" | sort -k2n
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.