在文件夹列表中查找文件夹位置编号
Find folder position number in folder listing
假设我有一个包含这些子文件夹的 /home
文件夹:
/home/alex
/home/luigi
/home/marta
我可以像这样列出并计算文件夹中的所有子文件夹:
ls 2>/dev/null -Ubad1 -- /home/* | wc -l
3
但如果文件夹(或 basename
)是 ===
luigi
,我需要找到位置(2
,在此示例中)
这在 bash 中可能吗?
在 William Pursell 发表评论后,这就完成了工作:
ls 2>/dev/null -Ubad1 -- /home/* | awk '/luigi$/{print NR}'
2
注意最后的 $
,这将避免像 joe
和 joey
这样的双打。
谢谢。
您可以在通配符扩展上使用 bash shell 循环,随时保留索引,并在基本目录名称匹配时报告索引:
index=1
for dir in /home/*
do
if [[ "$dir" =~ /luigi$ ]]
then
echo $index
break
fi
((index++))
done
这报告了“luigi”目录的位置(在 /home/*
的扩展中)——用目录分隔符 /
和行尾 $
锚定。
$ find /home/ -mindepth 1 -maxdepth 1 -type d | awk -F/ '$NF=="luigi" {print NR}'
2
$ find /home/ -mindepth 1 -maxdepth 1 -type d | awk -F/ '$NF=="alex" {print NR}'
1
最好使用 find 来获取子文件夹和一个列表来迭代索引:
subfolders=($(find /home -mindepth 1 -maxdepth 1 -type d))
Find 会得到真实路径,所以如果你需要 relative 你可以使用类似的东西:
luigi_folder=${subfolders[2]##*/}
假设我有一个包含这些子文件夹的 /home
文件夹:
/home/alex
/home/luigi
/home/marta
我可以像这样列出并计算文件夹中的所有子文件夹:
ls 2>/dev/null -Ubad1 -- /home/* | wc -l
3
但如果文件夹(或 basename
)是 ===
luigi
2
,在此示例中)
这在 bash 中可能吗?
在 William Pursell 发表评论后,这就完成了工作:
ls 2>/dev/null -Ubad1 -- /home/* | awk '/luigi$/{print NR}'
2
注意最后的 $
,这将避免像 joe
和 joey
这样的双打。
谢谢。
您可以在通配符扩展上使用 bash shell 循环,随时保留索引,并在基本目录名称匹配时报告索引:
index=1
for dir in /home/*
do
if [[ "$dir" =~ /luigi$ ]]
then
echo $index
break
fi
((index++))
done
这报告了“luigi”目录的位置(在 /home/*
的扩展中)——用目录分隔符 /
和行尾 $
锚定。
$ find /home/ -mindepth 1 -maxdepth 1 -type d | awk -F/ '$NF=="luigi" {print NR}'
2
$ find /home/ -mindepth 1 -maxdepth 1 -type d | awk -F/ '$NF=="alex" {print NR}'
1
最好使用 find 来获取子文件夹和一个列表来迭代索引:
subfolders=($(find /home -mindepth 1 -maxdepth 1 -type d))
Find 会得到真实路径,所以如果你需要 relative 你可以使用类似的东西:
luigi_folder=${subfolders[2]##*/}