我理解如何递归搜索文件或目录的层次结构,但无法弄清楚如何搜索层次结构并查找特定目录。
给出一条路径&像这些文件这样的文件:
/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
N.B。我知道从project_name
开始的下一个目录是spec/
或lib/
答案 0 :(得分:1)
纯粹的bash(没有子进程产生或其他命令)。根据您希望的灵活程度,您可能需要先考虑通过rootdir()
运行readlink -fn
函数的参数。解释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
答案 1 :(得分: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/'