We can find the full absolute path of a destination file using find keyword. In my case, I need the list of all immediate next directory to my given location which can lead me to my program log file named foo.log

For example, some of the paths may be:


For the above case, I need a list/array/vector anything like ['alpha', 'apple'] as my result as it contains all the possible immediate next folder to reach the destination file.

I'm new to Linux tools. I know, I can always create a brute force solution as I have the absolute-path as well as the given-path, but any optimized/better solution or any hint/idea in the right direction will do!

I don't want the first distinct folder, just the immediate folder to the given-location.

My brute force approach:

   for all the Absolute-path which can reach foo.log:
       Suffix-path = (Absolute-path - given-path)
       Append the Suffix-path[0] to result

2 Answers 2


%P format directive will give you the path directly after the starting-point:

find given-location/ -type f \
  -name 'foo.log' -printf %P\\n | cut -f1 -d /

You can append the output from find to an array using the += operator:

a=(); a+=( \
  $(find given-location/ -type f \
       -name 'foo.log' -printf %P\\n | cut -f1 -d / \
  ) \
); echo "${a[@]}"

The next example makes use of globstar **/; matches zero or many subdirectories.


shopt -s globstar nullglob
for b in given-location/**/foo.log; do
    readarray -t -d / -s 1 -n 1 -O ${#a[@]} a <<< "$b"
echo "${a[@]}"

Moving the start index with -O to the end of the array makes it possible to append new values.

  • -t Remove a trailing delim
  • -d Delim is used to terminate each input line, rather than newline.
  • -s Discard the first count lines read.
  • -n Copy at most count lines.
  • -O Begin assigning to array at index origin.

Get second field of a string with awk:

$ echo 'given-location/alpha/beta/gamma/foo.log' | awk -F/ '{print $2}'

awk command options used
-F/ : specify '/' as fields separator char
$2  : second field
  • 1
    Think he wants the second field from the beginning.
    – user986805
    Feb 12, 2021 at 6:14
  • @bac0n : oops, tks. Edited !
    – cmak.fr
    Feb 12, 2021 at 6:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .