簡體   English   中英

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

您只需要按數字部分排序。 一種方法可能是消除非數字部分並構建一個數組。 從好的方面來說,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[*]}"
}

如果您有兩個具有相同“數字”值的成員,則僅打印最后一個成員。 @BenjaminW建議將此類條目與換行符一起附加。 就像是…

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM