查找当前目录的直接下一个目录列表以到达目标文件?

Find the list of immediate next directory to the current directory for reaching a destination file?

我们可以使用 find 关键字找到目标文件的完整绝对路径。在我的例子中,我需要我当前位置的所有直接下一个目录的列表,这可以引导我找到名为 foo.log

的程序日志文件

例如,某些路径可能是:

current-location/alpha/beta/gamma/foo.log
current-location/apple/banana/foo.log
and so on...

对于上述情况,我需要一个 ['alpha', 'apple'] 的列表作为我的结果,因为它包含所有可能的直接下一个文件夹以到达目标文件。

我是 Linux 的新手。我知道,我总是可以创建一个蛮力解决方案,因为我有绝对路径和当前路径,但是任何 optimized/better 解决方案或任何 hint/idea 方向正确的解决方案都可以!

编辑:

我不想要第一个不同的文件夹,只想要当前位置的直接文件夹

我的蛮力方法:

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

怎么样(有点啰嗦):

find . -type f -name 'foo.log' | sed -nE "s#[^/]+/([^/]+)/.*##p;s#.*#'&'#" | paste -sd, - | sed -s 's/^/[/;s/$/]/'

或者:

find . -type f -name 'foo.log' -printf '%d %p\n' |awk -F '[ /]' '>1 {list=sprintf("%s7%s7", ((!list)?"":list ","),)} END {print "[" list "]"}'

只是@vgersh99回答的一个简单版本,概念是一样的(%P格式指令会在起点后直接给你路径):

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

您可以使用 += 运算符将 find 的输出追加到数组中:

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