bash 排序没有按期望按字段进行数字排序

bash 排序没有按期望按字段进行数字排序

我一直在尝试对文件名列表进行数字排序。

它们都被命名为

某物.txt~NUM~

我尝试过按以下方式排序

排序-t“〜”-k1 -k2n

但排序结果不对。如果我这样做

排序-n

然后它们按需要按数字排序,但文件句柄未排序。

这是一个测试文件

explanation.txt.~1~
explanation.txt.~2~
explanation.txt.~3~
explanation.txt.~4~
explanation.txt.~5~
explanation.txt.~6~
explanation.txt.~7~
explanation.txt.~8~
explanation.txt.~9~
explanation.txt.~11~
explanation.txt.~12~
explanation.txt.~13~
explanation.txt.~14~
explanation.txt.~15~
explanation.txt.~16~
explanation.txt.~17~
explanation.txt.~18~
explanation.txt.~19~
explanation.txt.~20~
presentation.txt.~10~
presentation.txt.~11~
presentation.txt.~12~
presentation.txt.~13~
presentation.txt.~14~
presentation.txt.~15~
presentation.txt.~16~
presentation.txt.~17~
presentation.txt.~18~
presentation.txt.~19~
presentation.txt.~1~
presentation.txt.~20~
presentation.txt.~21~
presentation.txt.~22~
presentation.txt.~2~
presentation.txt.~3~
presentation.txt.~4~
presentation.txt.~5~
presentation.txt.~6~
presentation.txt.~7~
presentation.txt.~8~
presentation.txt.~9~

排序为

explanation.txt.~11~
explanation.txt.~12~
explanation.txt.~13~
explanation.txt.~14~
explanation.txt.~15~
explanation.txt.~16~
explanation.txt.~17~
explanation.txt.~18~
explanation.txt.~19~
explanation.txt.~1~
explanation.txt.~20~
explanation.txt.~2~
explanation.txt.~3~
explanation.txt.~4~
explanation.txt.~5~
explanation.txt.~6~
explanation.txt.~7~
explanation.txt.~8~
explanation.txt.~9~
presentation.txt.~10~
presentation.txt.~11~
presentation.txt.~12~
presentation.txt.~13~
presentation.txt.~14~
presentation.txt.~15~
presentation.txt.~16~
presentation.txt.~17~
presentation.txt.~18~
presentation.txt.~19~
presentation.txt.~1~
presentation.txt.~20~
presentation.txt.~21~
presentation.txt.~22~
presentation.txt.~2~
presentation.txt.~3~
presentation.txt.~4~
presentation.txt.~5~
presentation.txt.~6~
presentation.txt.~7~
presentation.txt.~8~
presentation.txt.~9~

我正在运行 Sierra OSX。因此,特别是,sort -V对我来说不可用。我还知道如何使用 perl 脚本获得所需的结果。因此,问题不在于如何获得所需的结果,而在于如何使用“sort”来实现这一点。

答案1

你首先要排序仅有的按字段 1 排序,如果出现平局则查看字段 2:

sort -t'~' -k1,1 -k2,2n

当您使用 时-k1,您将按字段 1 排序取决于行尾。当您这样做时,没有平局,因此按字段 2 排序永远不会启动。

相关内容