如何使用bash腳本對字串+數字組合的字串進行排序?

如何使用bash腳本對字串+數字組合的字串進行排序?

這就是我要排序的資料。但sort將數字視為字串,數據沒有按我的預期排序。

/home/files/profile1
/home/files/profile10
/home/files/profile11
/home/files/profile12
/home/files/profile14
/home/files/profile15
/home/files/profile16
/home/files/profile2
/home /檔案/設定檔3
/主/檔案/設定檔4
/主/檔案/設定檔5
/主/檔案/設定檔6
/主/檔案/設定檔7
/主/檔案/設定檔8
/主/文件/設定檔9

我想將其排序為

/home/files/profile1
/home/files/profile2
/home/files/profile3
/home/files/profile4
/home/files/profile5
/home/files/profile6
/home/files/profile7
/home/files/profile8
/home /檔案/設定檔9
/家/檔案/設定檔10
/家/檔案/設定檔11
/家/檔案/設定檔12
/家/檔案/設定檔14
/家/檔案/設定檔15
/家/檔案/設定檔16

bash腳本有什麼好方法嗎?我不能在這裡使用 ruby​​ 或 python 腳本。

答案1

這非常類似於這個問題。問題在於,您有一個要排序的字母數字字段,並且-n沒有明智地對待它,但版本排序 ( -V) 卻這樣做了。因此使用:

sort -V

請注意,目前 GNU、FreeBSD 和 OpenBSD 排序實作都支援此功能。

答案2

您可以使用臨時哨兵字元來分隔數字:

$ sed 's/\([0-9]\)/;\1/' log | sort -n -t\; -k2,2 | tr -d ';'

這裡,哨兵字元是“;” - 它不能是您想要排序的任何檔案名稱的一部分 - 但您可以交換“;”與任何你喜歡的角色。您必須相應地更改sed,sorttr部分。

該管道的工作原理如下:該sed命令在任何數字之前插入標記,該sort命令將標記解釋為字段分隔符,使用第二個字段作為數字排序鍵進行排序,然後該tr命令再次刪除標記。

log表示輸入檔 - 您也可以將輸入透過管道傳輸到sed.

答案3

如果所有檔案名稱在最終數字部分之前都有相同的前綴,則在排序時忽略它:

sort -k 1.20n

(20 是第一個數字的位置。它是 1 加 的長度/home/files/profile。)

如果你有幾個不同的非數字部分,插入哨兵

相關內容