shell 如何按版本号对文件名进行排序?

jm81lzqq  于 6个月前  发布在  Shell
关注(0)|答案(8)|浏览(66)

在目录“数据”是这些文件:
command-1.9a-setup
command-2.0a-setup
command-2.0c-setup
command-2.0-setup
我想对文件进行排序,得到这样的结果:
command-1.9a-setup
command-2.0-setup
command-2.0a-setup
command-2.0c-setup
我尝试了这个

find /data/ -name 'command-*-setup' | sort --version-sort --field-separator=- -k2

字符串
但结果是
command-1.9a-setup
command-2.0a-setup
command-2.0c-setup
command-2.0-setup
我找到的唯一能让我得到想要的输出的方法是

tree -v /data


我怎么能得到与排序的输出在想要的顺序?

pu82cl6c

pu82cl6c1#

*编辑: 事实证明,伯努瓦是在正确的轨道上排序和罗兰倾斜的平衡 *

你只需要告诉sort只考虑 * 字段2(添加“,2”):

find ... | sort --version-sort --field-separator=- --key=2,2

字符串

*原始答案: 忽略 *

如果你的文件名中没有一个在连字符之间包含空格,你可以尝试这样做:

find ... | sed 's/.*-\([^-]*\)-.*/\1 \0/;s/[^0-9] /.&/' | sort --version-sort --field-separator=- --key=2 | sed 's/[^ ]* //'


第一个sed命令使行看起来像这样(我添加了“10”以显示排序是数字的):

1.9.a command-1.9a-setup
2.0.c command-2.0c-setup
2.0.a command-2.0a-setup
2.0 command-2.0-setup
10 command-10-setup


第二个sed命令从每一行中删除前缀版本号。
有很多方法会失败。

q1qsirdb

q1qsirdb2#

如果你指定只考虑第二个字段(-k2),不要抱怨它不考虑第三个字段。
在你的例子中,运行sort --version-sort而不带任何其他参数,也许这样会更好。

x7yiwoj4

x7yiwoj43#

看起来像这样工作:

find /data/ -name 'command-*-setup' | sort -t - -V -k 2,2

字符串
不是用sort,但它可以工作:

tree -ivL 1 /data/ | perl -nlE 'say if /\Acommand-[0-9][0-9a-z.]*-setup\z/'


-v:按版本对输出进行排序
-i:使树不打印缩进线
-L级:目录树的最大显示深度

ukdjmx9f

ukdjmx9f4#

另一种方法是填补你的数字。
这个例子将所有数字填充为8位数字。然后,它进行一个普通的字母数字排序。然后,它删除填充。

$ pad() { perl -pe 's/(\d+)/0000000\1/g' | perl -pe 's/0*(\d{8})/\1/g'; }
$ unpad() { perl -pe 's/0*([1-9]\d*|0)/\1/g'; }
$ cat files | pad | sort | unpad
command-1.9a-setup
command-2.0-setup
command-2.0a-setup
command-2.0c-setup
command-10.1-setup

字符串
为了深入了解这是如何工作的,让我们看看填充的排序结果:

$ cat files | pad | sort
command-00000001.00000009a-setup
command-00000002.00000000-setup
command-00000002.00000000a-setup
command-00000002.00000000c-setup
command-00000010.00000001-setup


您将看到,所有数字都被很好地填充为8位数,字母数字排序将文件名按所需的顺序排列。

ao218c7q

ao218c7q5#

$ cat files
command-1.9a-setup
command-2.0c-setup
command-10.1-setup
command-2.0a-setup
command-2.0-setup

$ cat files | sort -t- -k2,2 -n
command-1.9a-setup
command-2.0-setup
command-2.0a-setup
command-2.0c-setup
command-10.1-setup

$ tac files | sort -t- -k2,2 -n
command-1.9a-setup
command-2.0-setup
command-2.0a-setup
command-2.0c-setup
command-10.1-setup

字符串

4ngedf3f

4ngedf3f6#

旧帖子,但... ls -l --sort=version可能会有所帮助(尽管对于OP的示例,排序与RHEL 7.2中的ls -l相同):

command-1.9a-setup
command-2.0a-setup
command-2.0c-setup
command-2.0-setup

字符串
我猜是YMMV。

ej83mcc0

ej83mcc07#

我有一个文件夹中的文件,需要得到这些名称的排序顺序,根据数量.例如-

abc_dr-1.txt
hg_io-5.txt
kls_er_we-3.txt
sd-4.txt
sl_rt_we_yh-2.txt

字符串
我需要根据数字来排序。所以我用这个来排序。

ls -1 | sort -t '-' -nk2


它给我的文件是根据编号排序的。

wyyhbhjk

wyyhbhjk8#

version-sort可以很容易地用jq实现:

$ ls -1 command-*-setup
command-1.9a-setup
command-10-setup
command-2.0-setup
command-2.0a-setup
command-2.0c-setup

个字符

相关问题