'Find folder position number in folder listing
Suppose i have a /home folder with these sub-folders:
/home/alex
/home/luigi
/home/marta
I can list and count all sub-folders in a folder like this:
ls 2>/dev/null -Ubad1 -- /home/* | wc -l
3
But I need to find the position (2, in this example) if folder (or basename) is === luigi
Is this possible in bash?
Solution 1:[1]
After William Pursell comment, this does the job:
ls 2>/dev/null -Ubad1 -- /home/* | awk '/luigi$/{print NR}'
2
Note the $ at the end, this will avoid doubles like joe and joey.
Thanks.
Solution 2:[2]
You could just use a bash shell loop over the wildcard expansion, keeping an index as you go, and report the index when the base directory name matches:
index=1
for dir in /home/*
do
if [[ "$dir" =~ /luigi$ ]]
then
echo $index
break
fi
((index++))
done
This reports the position (among the expansion of /home/*) of the "luigi" directory -- anchored with the directory separator / and the end of the line $.
Solution 3:[3]
$ 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
Solution 4:[4]
Better use find to get subfolders and a list to iterate with indexes:
subfolders=($(find /home -mindepth 1 -maxdepth 1 -type d))
Find will get realpath, so if you need relative you can use something like:
luigi_folder=${subfolders[2]##*/}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | CrazyRabbit |
| Solution 2 | Jeff Schaller |
| Solution 3 | ufopilot |
| Solution 4 | darkmaster |
