Ken Taylor Asked: 2023-05-13 02:28:54 +0800 CST2023-05-13 02:28:54 +0800 CST 2023-05-13 02:28:54 +0800 CST 对文件名列表进行排序,使子目录中的文件在父目录中的文件之前列出 772 我有一个包含文件列表的文本文件,例如: file A1/file A1/B1/file A2/file 如何对其进行排序,使子目录中的文件在父目录中的其他文件之前列出? A1/B1/file A1/file A2/file file filenames 3 个回答 Voted Gilles Quénot 2023-05-13T02:51:04+08:002023-05-13T02:51:04+08:00 这里有一个简单的方法: awk 'BEGIN{FS="/"; OFS="\t"}{print NF, $0}' file | sort -rn | cut -f2- A1/B1/file A2/file A1/file file 应该适用于简单的情况,比如你的问题。 如果您还想按目录排序: awk 'BEGIN{FS="/"; OFS="\t"}{print NF, $0}' file | sort -k1,1rn -k2 | cut -f2- A1/B1/file A1/file A2/file file Best Answer Stéphane Chazelas 2023-05-16T03:02:51+08:002023-05-16T03:02:51+08:00 zsh具有odglob 限定符以oerder glob 扩展depth-first, $ print -rC1 -- **/file(Nod) A2/file A1/B1/file A1/file file 如果使用限定符将文件列表加载到 glob 扩展中,则可以将其应用于任意文件列表e。 $ print -rC1 -- /(Ne['reply=( ${(f)"$(<your-file)"} )']od) A2/file A1/B1/file A1/file file 也按名称排序on: $ print -rC1 -- /(Ne['reply=( ${(f)"$(<your-file)"} )']odon) A1/B1/file A1/file A2/file file Jim L. 2023-05-16T02:20:57+08:002023-05-16T02:20:57+08:00 为了扩展@Kusalananda 的见解,如果这些文件名确实是现存目录树的完整内容,find可以做你想做的: 鉴于: $ find . ./f2 ./A1 ./A1/B1 ./A1/B1/f2 ./A1/B1/f1 ./A1/f2 ./A1/f1 ./A2 ./A2/B1 ./A2/B1/C1 ./A2/B1/C1/f2 ./A2/B1/C1/f1 ./A2/f2 ./A2/f1 ./f1 GNUfind可以: $ find . -depth -type d -exec find {} -maxdepth 1 -not -type d \; ./A1/B1/f2 ./A1/B1/f1 ./A1/f2 ./A1/f1 ./A2/B1/C1/f2 ./A2/B1/C1/f1 ./A2/f2 ./A2/f1 ./f2 ./f1 如果您关心目录中文件的排序,GNU find 会让您失望,因为它无法控制排序。您可能必须执行以下操作: $ find . -depth -type d -exec sh -c 'find {} -maxdepth 1 -not -type d | sort' \; ./A1/B1/f1 ./A1/B1/f2 ./A1/f1 ./A1/f2 ./A2/B1/C1/f1 ./A2/B1/C1/f2 ./A2/f1 ./A2/f2 ./f1 ./f2 FreeBSD 和 NetBSD 上的实用程序find将识别标志-s以按文件名排序: $ find . -depth -type d -exec find -s {} -maxdepth 1 -not -type d \; ./A1/B1/f1 ./A1/B1/f2 ./A1/f1 ./A1/f2 ./A2/B1/C1/f1 ./A2/B1/C1/f2 ./A2/f1 ./A2/f2 ./f1 ./f2 正如@StéphaneChazelas 在评论中指出的那样,该-s标志在 OpenBSD 中不可用。即使它可用,find -s也可能会根据您的语言环境等而崩溃,如手册页所述: 注意:'find -s' 和 'find | sort' 可能会给出不同的结果。
这里有一个简单的方法:
应该适用于简单的情况,比如你的问题。
如果您还想按目录排序:
zsh
具有od
glob 限定符以o
erder glob 扩展d
epth-first,如果使用限定符将文件列表加载到 glob 扩展中,则可以将其应用于任意文件列表
e
。也按名称排序
on
:为了扩展@Kusalananda 的见解,如果这些文件名确实是现存目录树的完整内容,
find
可以做你想做的:鉴于:
GNU
find
可以:如果您关心目录中文件的排序,GNU find 会让您失望,因为它无法控制排序。您可能必须执行以下操作:
FreeBSD 和 NetBSD 上的实用程序
find
将识别标志-s
以按文件名排序:正如@StéphaneChazelas 在评论中指出的那样,该
-s
标志在 OpenBSD 中不可用。即使它可用,find -s
也可能会根据您的语言环境等而崩溃,如手册页所述: