Bash:列出按文件包含的数量排序的文件

Bash: list files ordered by the number they contain

目标

我有一系列具有不同名称的文件。每个文件的名称都包含一个由 1 到 4 位数字组成的唯一整数。我想订购文件(通过显示全名),但按文件包含的编号排序。

例子

文件..

Hello54.txt
piou2piou.txt
hap_1002_py.txt
JustAFile_78.txt
darwin2012.txt

.. 应列为

piou2piou.txt
Hello54.txt
JustAFile_78.txt
hap_1002_py.txt
darwin2012.txt

您只需按数字部分排序即可。一种方法可能是消除 non-numeric 部分并构建一个数组。从好的方面来说,bash 具有稀疏数组,因此无论您 添加 成员的顺序如何,它们都会以正确的顺序出现。伪代码:

array[name_with_non_numerics_stripped]=name
print array

我快速而不仔细的实现:

sortnum() {
    # Store the output in a sparse array to get implicit sorting
    local -a map
    local key
    # (REPLY is the default name `read` reads into.)
    local REPLY 
    while read -r; do
        # Substitution parameter expansion to nuke non-numeric chars
        key="${REPLY//[^0-9]}"
        # If key occurs more than once, you will lose a member.
        map[key]="$REPLY"
    done
    # Split output by newlines.
    local IFS=$'\n'
    echo "${map[*]}"
}

如果您有两个具有相同 "numeric" 值的成员,则只会打印最后一个。 @BenjaminW 建议将这些条目与换行符一起附加。像……

[[ ${map[key]} ]] && map[key]+=$'\n'
map[key]+="$REPLY"

…代替上面的map[key]="$REPLY"