使用自定义排序顺序在Unix中对字母数字字符串进行排序 [英] Sort alphanumeric string in Unix using custom sort order
问题描述
我有一个名字列表,名字不正确.如何使用字母部分的自定义排序顺序以正确的字母数字顺序获取它们?
I have a list of names, which are out of order. How can I get them in the correct alphanumeric order, using a custom sort order for the alphabetical part?
我的文件numbers.txt
:
alpha-1
beta-3
alpha-10
beta-5
alpha-5
beta-1
gamma-7
gamma-1
delta-10
delta-2
主要要点是我的脚本应该认识到它应该在beta
之前打印alpha
,在gamma
之前打印beta
,并且在delta
之前打印gamma
.
The main point is that my script should recognize that it should print alpha
before beta
, and beta
before gamma
, and gamma
before delta
.
也就是说,单词应该根据它们表示的希腊字母中字母的顺序进行排序.
That is, the words should be sorted based on the order of the letters in the Greek alphabet they represent.
预期订单:
alpha-1
alpha-5
alpha-10
beta-1
beta-3
beta-5
gamma-1
gamma-7
delta-2
delta-10
PS:我尝试使用sort -n numbers.txt
,但这不符合我的需求.
PS: I tried with sort -n numbers.txt
, but it doesn't fit my need.
推荐答案
您可以如下使用辅助awk
命令:
You can use an auxiliary awk
command as follows:
awk -F- -v keysInOrder="alpha,beta,gamma,delta" '
BEGIN {
split(keysInOrder, a, ",")
for (i = 1; i <= length(a); ++i) keysToOrdinal[a[i]] = i
}
{ print keysToOrdinal[$1] "-" $0 }
' numbers.txt | sort -t- -k1,1n -k3,3n | cut -d- -f2-
-
awk
命令用于:The
awk
command is used to:-
将自定义键映射到反映所需排序顺序的数字上;请注意,键的完整列表必须按顺序通过变量
keysInOrder
传递.
也使用分隔符
-
将数字作为辅助列添加到输入中.例如,beta-3
变为2-beta-3
,因为beta
在排序键的有序列表中位于位置 2 .prepend the numbers to the input as an auxiliary column, using separator
-
too; e.g.,beta-3
becomes2-beta-3
, becausebeta
is in position 2 in the ordered list of sort keys.sort
然后按照映射的数字以及第二列中的原始数字对awk
的输出进行排序,从而产生所需的自定义排序顺序.sort
then sortsawk
's output by the mapped numbers as well as the original number in the 2nd column, yielding the desired custom sort order.cut
然后删除辅助.再次映射数字.cut
then removes the aux. mapped numbers again.这篇关于使用自定义排序顺序在Unix中对字母数字字符串进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
-