递归查找目录树每个分支中的每个第一个文件

递归查找目录树每个分支中的每个第一个文件

考虑以下目录列表:

/a/1
/a/2
/a/3
/b/1
/b/2
/b/3/a
/b/3/b
/c/a.whatever
/c/b
/c/c

我想要一个命令,它可以找到每个目录(包括嵌套)中的第一个(按字母数字排序)文件并提供以下输出:

/a/1
/b/1
/b/3/a
/c/a.whatever

这看起来像是一份工作,find但我的咖啡快喝完了。释放忍者!

答案1

另一种解决方案 - 应该使用路径中的空格

find . -type d -exec sh -c 'find "{}" -maxdepth 1 -type f | sort | head -n 1' ";"

顺便提一下,我发现ls缺少输出完整路径的选项,并且只列出文件(而不是目录):(

答案2

利用awk我想到了这个:

查找 -type d | awk'{print“查找“$0”-type f | head -1”}'| sh | uniq

uniq变得必要,因为 find 搜索子目录...可能可以通过某种方式使用额外的 find 参数来解决这个问题。

编辑
没有 uniq 的版本

查找 -type d | awk'{print“find“$0”-maxdepth 1 -type f | head -1”}'| sh

请注意,您可以轻松调整每个目录的打印文件数量。要预先对文件进行排序,请使用:

查找 -type d | awk'{print“查找“$0”-maxdepth 1-type f | sort | head -1”}'| sh

答案3

好吧,经过一番尝试,我自己的忍者技能稍微恢复了一点,并想出了这个蒸锅:

find -type d | xargs -I{} bash -c "find {} -maxdepth 1 -type f | sort | head -1" | sort

虽然不是最优雅的文件系统查询,但是它输出的结果符合我的期望。

相关内容