排序find命令以遵守Unix中的自定义顺序 [英] Sort a find command to respect a custom order in Unix
问题描述
我有一个脚本(通过find
)输出文件路径,我想根据非常具体的自定义逻辑 对其进行排序:
I have a script that outputs file paths (via find
), which I want to sort based on very specific custom logic:
-
第一排序键: 我希望根据我提供的键列表使用 custom 排序对第二个(如果存在的话)和第三个
-
分隔的字段进行排序-但排除后缀.
在下面的示例输入中,键列表为:
rp,alpha,beta-ri,beta-rs,RC
1st sort key: I want the 2nd and, if present, the 3rd
-
-separated field to be sorted using custom ordering based on a list of keys I supply - but excluding a numerical suffix.
With the sample input below, the list of keys is:
rp,alpha,beta-ri,beta-rs,RC
第二个排序键:数字按每行上的跟踪编号进行排序.
2nd sort key: numeric sorting by the trailing number on each line.
给出以下示例输入(请注意,每行的/foo/bar/test/example/8.2.4.0
前缀是附带的):
Given the following sample input (note that the /foo/bar/test/example/8.2.4.0
prefix of each line is incidental):
/foo/bar/test/example/8.2.4.0-RC10
/foo/bar/test/example/8.2.4.0-RC2
/foo/bar/test/example/8.2.4.0-RC1
/foo/bar/test/example/8.2.4.0-alpha10
/foo/bar/test/example/8.2.4.0-beta-ri10
/foo/bar/test/example/8.2.4.0-beta-ri2
/foo/bar/test/example/8.2.4.0-beta-rs10
/foo/bar/test/example/8.2.4.0-beta-rs2
/foo/bar/test/example/8.2.4.0-alpha2
/foo/bar/test/example/8.2.4.0-rp10
/foo/bar/test/example/8.2.4.0-rp2
我希望:
/foo/bar/test/example/8.2.4.0-rp2
/foo/bar/test/example/8.2.4.0-rp10
/foo/bar/test/example/8.2.4.0-alpha2
/foo/bar/test/example/8.2.4.0-alpha10
/foo/bar/test/example/8.2.4.0-beta-ri2
/foo/bar/test/example/8.2.4.0-beta-ri10
/foo/bar/test/example/8.2.4.0-beta-rs2
/foo/bar/test/example/8.2.4.0-beta-rs10
/foo/bar/test/example/8.2.4.0-RC1
/foo/bar/test/example/8.2.4.0-RC2
/foo/bar/test/example/8.2.4.0-RC10
推荐答案
使用我对原始问题的回答:
./your-script | awk -v keysInOrder='rp,alpha,beta-ri,beta-rs,RC' '
BEGIN {
FS=OFS="-"
keyCount = split(keysInOrder, a, ",")
for (i = 1; i <= keyCount; ++i) keysToOrdinal[a[i]] = i
}
{
sortKey = $2
if (NF == 3) sortKey = sortKey FS $3
sub(/[0-9]+$/, "", sortKey)
auxFieldPrefix = "|" FS
if (NF == 2) auxFieldPrefix = auxFieldPrefix FS
sub(/[0-9]/, auxFieldPrefix "&", $NF)
sortOrdinal = sortKey in keysToOrdinal ? keysToOrdinal[sortKey] : keyCount + 1
print sortOrdinal, $0
}
' | sort -t- -k1,1n -k3,3 -k5,5n | sed 's/^[^-]*-//; s/|-\{1,2\}//'
./your-script
表示生成您要排序的输出的任何命令.
./your-script
represents whatever command produces the output you want to sort.
请注意,辅助.字符|
用于简化排序,并且假定该字符未出现在输入中-考虑到文件系统路径通常不包含管道字符,因此这是合理安全的.
Note that an aux. character, |
, is used to facilitate sorting, and the assumption is that this character doesn't appear in the input - which should be reasonable safe, given that filesystem paths usually don't contain pipe characters.
在排序键列表中没有的任何字段2值(无数字后缀),使用字母顺序对字段2/3的值之后进行排序在其中排序.
Any field 2 values (sans numeric suffix) that aren't in the list of sort keys, sort after the field 2/3 values that are, using alphabetic sorting among them.
这篇关于排序find命令以遵守Unix中的自定义顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!