Bash在最小深度的子文件夹中查找文件夹
问题描述:
我有这个脚本可以轻松移入文件夹。 我的问题是,如果我搜索tests
,但该文件夹位于我当前的文件夹和子文件夹内,如果先搜索子文件夹,它将移动到子文件夹中的测试中。但它总是应该从子文件夹结构进入“最低”匹配。有任何想法吗?Bash在最小深度的子文件夹中查找文件夹
function f {
if [[ -d $(find . -name $1 -type d) ]]; then
cd $(find . -name $1 -type d)
else
cd $(find ~ -name $1 -type d)
fi
}
答
你的问题对我有点不清楚。只是在寻找类似
cd "$(find . -depth -type d -name "$1" -print -quit)"
这将遍历DFS秩序和cd
目录到第一个匹配$1
找到。
答
试试这个脚本:
cd $(for each in `find . -name $1 -type d`
do
cnt=`echo $each | sed 's:[^/]::g' | awk '{print length}'`
echo "$cnt $each"
done | sort -g | awk '{print $2}' | head -1)
-
find
在for循环查找所有的目录名称为$ 1 -
cnt
变量计数没有。路径中的“/”。 -
sort -g
根据cnt
变量对输出进行排序。 -
head -1
返回排序列表中的第一项,它将是“最低”匹配。
+0
请注意,如果文件名有空格,这将失败。 – BroSlow 2014-09-26 22:11:41
你的标题说'最不深',你的问题说'最低'? – BroSlow 2014-09-26 22:39:55
请注意,“-type d”搜索目录,“-type f”搜索文件,但没有搜索“folders”的选项......因为它们被称为“目录”! – 2014-09-26 22:53:57