9

我有一个文件列表,最后有一个版本号,我需要排序

/this/is/a/file/path/product-2.0/file/name/7
/this/is/a/file/path/product-2.0/file/name/10
/this/is/a/file/path/product-2.0/file/name/12
/this/is/a/file/path/product-2.0/file/name/13
/this/is/a/file/path/product-2.0/file/name/6
/this/is/a/file/path/product-2.0/file/name/8
/this/is/a/file/path/product-2.0/file/name/9

当我通过 grep 管道它时,它的排序如下:

echo $files | sort -n
/this/is/a/file/path/product-2.0/file/name/10
/this/is/a/file/path/product-2.0/file/name/12
/this/is/a/file/path/product-2.0/file/name/13
/this/is/a/file/path/product-2.0/file/name/6
/this/is/a/file/path/product-2.0/file/name/7
/this/is/a/file/path/product-2.0/file/name/8
/this/is/a/file/path/product-2.0/file/name/9

我认为 -n 被文件名中的第一个数字弄糊涂了。

如何按最后一个数字对其进行数字排序

4

5 回答 5

22
Kaizen ~/so_test $ cat ztestfile1 | sort -t'/' -n -k10
/this/is/a/file/path/product-2.0/file/name/6
/this/is/a/file/path/product-2.0/file/name/7
/this/is/a/file/path/product-2.0/file/name/8
/this/is/a/file/path/product-2.0/file/name/9
/this/is/a/file/path/product-2.0/file/name/10
/this/is/a/file/path/product-2.0/file/name/12
/this/is/a/file/path/product-2.0/file/name/13

这有帮助吗?

替代方式,即独立于职位.....

 Kaizen ~/so_test  $ cat ztestfile1 | sort -V
 /this/is/a/file/path/product-2.0/file/name/6
 /this/is/a/file/path/product-2.0/file/name/7
 /this/is/a/file/path/product-2.0/file/name/8
 /this/is/a/file/path/product-2.0/file/name/9
 /this/is/a/file/path/product-2.0/file/name/10
 /this/is/a/file/path/product-2.0/file/name/12
 /this/is/a/file/path/product-2.0/file/name/13

请注意它的 -V (Capital) 选项在排序中查看字符串中的数字差异以排序.....就像在版本号中一样。

手册页文本::

   -V, --version-sort
          natural sort of (version) numbers within text
于 2013-06-05T16:32:45.377 回答
5

您可以/用作列分隔符:

sort -n -t/ -k 10
于 2013-06-05T16:31:14.557 回答
2

用于awk将最后一个字段放在sort第一个字段前面,然后申请cut摆脱第一个字段。使用here document下面的示例

awk -F'/' '{print($NF"/"$0)}' <<! | sort -k1n,1n -t'/' | cut -f2- -d'/'
> /this/is/a/file/path/product-2.0/file/name/7
> /this/is/a/file/path/product-2.0/file/name/10
> /this/is/a/file/path/product-2.0/file/name/12
> /this/is/a/file/path/product-2.0/file/name/13
> /this/is/a/file/path/product-2.0/file/name/6
> /this/is/a/file/path/product-2.0/file/name/8
> /this/is/a/file/path/product-2.0/file/name/9
> !
/this/is/a/file/path/product-2.0/file/name/6
/this/is/a/file/path/product-2.0/file/name/7
/this/is/a/file/path/product-2.0/file/name/8
/this/is/a/file/path/product-2.0/file/name/9
/this/is/a/file/path/product-2.0/file/name/10
/this/is/a/file/path/product-2.0/file/name/12
/this/is/a/file/path/product-2.0/file/name/13
于 2013-06-05T16:32:42.930 回答
0

或者使用 perl 或 ruby​​ 之类的单行代码:

ruby -we 'print *readlines.sort_by{|x| File.basename(x).to_i}'
于 2013-06-05T16:52:19.170 回答
-1

这使您可以使用/作为字段分隔符的路径中的最后一项进行排序,获取最后一个值并将其放在行首,排序,然后从行首删除该值。

cat data | awk 'BEGIN { FS="/"} { print $(NF) " " $0 }' | sort -n | sed 's/^.*\s//g'
于 2013-06-05T16:33:42.270 回答