gpt4 book ai didi

bash - 查找所有目录,不包含其他目录

转载 作者:行者123 更新时间:2023-12-03 20:24:45 25 4
gpt4 key购买 nike

目前:

$ find -type d
./a
./a/sub
./b
./b/sub
./b/sub/dub
./c/sub
./c/bub
我需要:
$ find -type d -not -contains -type d
./a/sub
./b/sub/dub
./c/sub
./c/bub
如何排除包含其他(子)目录但不为空(包含文件)的目录?

最佳答案

您可以 find只有 2 个链接(或更少)的叶目录,然后检查每个找到的目录是否包含一些文件。
像这样的东西:

# find leaf directories
find -type d -links -3 -print0 | while read -d '' dir
do
# check if it contains some files
if ls -1qA "$dir" | grep -q .
then
echo "$dir"
fi
done
或者干脆:
find -type d -links -3 ! -empty
请注意,您可能需要 find选项 -noleaf在某些文件系统上,例如 CD-ROM 或某些 MS-DOS 文件系统。不过,它在 WSL2 中没有它也能工作。
文件系统目录总是有 1 个链接,所以使用 -links不会在那里工作。
慢得多,但与文件系统无关, find基于版本:
prev='///' # some impossible dir

# A depth first find to collect non-empty directories
readarray -d '' dirs < <(find -depth -type d ! -empty -print0)

for dir in "${dirs[@]}"
do
dirterm=$dir'/'

# skip if it matches the previous dir
[[ $dirterm == ${prev:0:${#dirterm}} ]] && continue

# skip if it has sub directories
[[ $(find "$dir" -mindepth 1 -maxdepth 1 -type d -print -quit) != '' ]] && continue

echo "$dir"
prev=$dir
done # add "| sort" if you want the same order as a "find" without "-depth"

关于bash - 查找所有目录,不包含其他目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63451128/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com