2013-10-18 59 views
0

我明白如何递归搜索文件或目录的层次结构,但无法弄清楚如何搜索层次结构并找到特定的目录。通过目录路径搜索找到一个特定的目录

给定一个路径&文件如这些家伙:

/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/

+2

你究竟在做什么*试图完成什么?当然有更好的办法 - 但我们必须知道你为什么要这样做。我有一种感觉,这将会变成一个[XY问题](http://www.perlmonks.org/?node_id=542341)。 –

+0

学习了新的'<! - language:none - >'谢谢:-) –

+2

所以你正在寻找文件路径列表的共同祖先? – damienfrancois

回答

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 
+0

它的功能就像是一种魅力,但我正努力让自己的头部完全发挥它的作用。你能给我一个快速的简要介绍。谢谢。 – dwkns

+0

http://www.tldp.org/LDP/abs/html/abs-guide.html#VARMATCH – bobah

0

您可以使用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/' 
+0

问题是没有*文件*只是一个文件 - 层次结构即没有文件解析。 –