Reputation: 2459
I understand how to recursively search down a hierarchy for a file or directory, but can't figure out how to search up the hierarchy and find a specific directory.
Given a path & file such as these fellas :
/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
How using the terminal can I get :
/Users/username/projects/project_name
N.B. I know that the next directory down from project_name
is spec/
or lib/
Upvotes: 0
Views: 396
Reputation: 18864
Pure bash (no sub-processes spawning or other commands). Depending on how flexible you want it to be you may want to consider running the argument of rootdir()
function through readlink -fn
first. Explained 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
Upvotes: 1
Reputation: 11
you can use perl:
cat file | perl -pe "s#(.+)(?:spec|lib).+#\1#"
where in file: /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
or you can use sed:
cat file | sed 's/\(^.*\)\(spec\|lib\).*/\1/'
Upvotes: 0