【问题标题】:Find directory path up in hierarchy recursively on Ruby在 Ruby 上递归查找层次结构中的目录路径
【发布时间】:2020-08-23 00:51:12
【问题描述】:

我想从当前目录开始递归查找名称的目录并获取它的绝对路径。我不知道哪个目录包含我需要的内容。所以我必须检查每个上层目录是否包含我需要的内容。

例如我有这样的目录树:

.
├── root
├── ...
├── someDir000
│   └── ...
│   └── someDir001
│       ├── otherDir000
│       └── dirPathIWantToFind
│       └── ...
├── someDir002
│   ├── anotherDir000
│   └── anotherDir001
│   ├── myCurrentDir

我目前在 myCurrentDir 中,想为 ** dirPathIWantToFind** 找到路径,所以应该是 /root/someDir000/someDir001/dirPathIWantToFind

我知道可以从当前目录递归下降,但是如何向上呢?

【问题讨论】:

  • 是的,我看到了这个答案,但它只列出了当前 DOWN 的目录。我需要像 bash cd .. 一样向上,直到到达“dirIWantToFind”
  • 两个文件的公共根是否已知?
  • 是的,它在任何 Unix 系统中都是一个全局根,就像根一样

标签: ruby


【解决方案1】:
Dir.glob(Pathname('/root').join('**/**/dirPathIWantToFind'))

Dir.glob。但请注意 - 这可能需要相当长的时间,具体取决于文件系统的大小。

【讨论】:

  • 谢谢!它有效,但我错了。对不起。我改了。
  • 如果从根目录开始,它可能是一个很深的层次结构,里面有很多目录。是否可以相反并从当前目录开始?就我而言,它应该短得多。我正在考虑更改为上层目录,检查它是否包含我需要获取路径的内容,如果没有,则再次更改上层。
  • 您可以使用Pathname#ascend 遍历目录,然后在每一步调用Dir.glob(Pathname(current_path).join('**/**/dirPathIWantToFind')) 直到找到目录。
猜你喜欢
  • 2017-12-17
  • 1970-01-01
  • 1970-01-01
  • 2014-01-25
  • 2015-11-23
  • 1970-01-01
  • 2013-11-22
  • 2017-02-04
  • 1970-01-01
相关资源
最近更新 更多