【问题标题】:Search up through directory path to find a specific directory通过目录路径向上搜索以找到特定目录
【发布时间】:2013-10-18 21:34:27
【问题描述】:

我了解如何在层次结构中递归搜索文件或目录,但不知道如何向上搜索层次结构并找到特定目录。

给定一个路径和文件,例如这些家伙:

/Users/username/projects/project_name/lib/sub_dir/file.rb
/Users/username/projects/project_name/lib/sub_dir/2nd_sub_dir/3rd_sub_dir/file.rb
/Users/username/projects/project_name/spec/sub_dir/file.rb

如何使用终端:

/Users/username/projects/project_name

注意我知道project_name 的下一个目录是spec/lib/

【问题讨论】:

  • 实际上想要完成什么?当然有更好的方法——但我们必须知道你为什么要这样做。我有一种感觉,这将变成XY problem
  • 通过<!-- language: none --> 学到了一些新东西,谢谢 :-)
  • 所以您正在寻找文件路径列表的共同祖先?
  • @FredrikPihl 是的 :-) 我实际上将其更改为 <!-- language-all: none -->,因此它适用于以下所有代码块。
  • @JonathonReinhart - 更好。我从现在开始使用那个

标签: bash unix command-line terminal


【解决方案1】:

纯 bash(没有子进程产生或其他命令)。根据您希望它的灵活性,您可能需要考虑首先通过readlink -fn 运行rootdir() 函数的参数。解释here

#!/bin/bash

function rootdir {
  local filename=$1
  local parent=${filename%%/lib/*}
  if [[ $filename == $parent ]]; then
    parent=${filename%%/spec/*}
  fi
  echo $parent
}

# test:
#  rootdir /Users/username/projects/project_name/lib/sub_dir/file.rb
#  rootdir /Users/username/projects/project_name/spec/sub_dir/file.rb
#  rootdir /Users/username/projects/project_name/lib/sub_dir/2nd_sub_dir/3rd_sub_dir/file.rb
# output:
#  /Users/username/projects/project_name
#  /Users/username/projects/project_name
#  /Users/username/projects/project_name

【讨论】:

  • 它就像一个魅力,但我正在努力弄清楚它是如何做的。你能不能给我一个快速的纲要。谢谢。
【解决方案2】:

你可以使用 perl:

cat file | perl -pe "s#(.+)(?:spec|lib).+#\1#"

在文件中的位置: /Users/username/projects/project_name/lib/sub_dir/file.rb /Users/username/projects/project_name/lib/sub_dir/2nd_sub_dir/3rd_sub_dir/file.rb /Users/username/projects/project_name/spec/sub_dir/file .rb

或者你可以使用 sed:

cat file | sed 's/\(^.*\)\(spec\|lib\).*/\1/'

【讨论】:

  • 问题是没有 file 只是一个文件层次结构,即没有要解析的文件。
猜你喜欢
  • 1970-01-01
  • 2014-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-25
相关资源
最近更新 更多