Home > Net >  Find folder position number in folder listing
Find folder position number in folder listing

Time:05-19

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?

CodePudding user response:

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.

CodePudding user response:

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 $.

CodePudding user response:

$ 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

CodePudding user response:

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]##*/}
  •  Tags:  
  • bash
  • Related