1

How can I find the path of a parent directory with a particular name? For instance, say I have directory /a/b/c/d/e/f/g and I want to find the parent directory with name c, I would want this to return /a/b/c.

The use case is that I'm within a fairly nested directory structure, and I don't want to have to have the difficult to read string of ../../.., which I would also need to make sure to change when I updated the nesting level of the directory structure in the future.

Not a dealbreaker, but if there were two ancestor directories with the given name, I would ideally want the one with the longest path. i.e. /a/b/c/d/e/c/f/g should ideally return /a/b/c/d/e/c instead of /a/b/c.

2

The solution is to use parameter substitution, twice.

We start by storing the pathname of the directory in a variable (if you're dealing with the current working directory, you can skip this and use PWD in place of p later):

$ p=/a/b/c/d/e/c/f/g

We may then remove the longest prefix string that matches */c/ from this:

$ echo "${p##*/c/}"
f/g

We then realize that if this result was deleted from the end of $p, we would get the result we want:

$ echo "${p%${p##*/c/}}"
/a/b/c/d/e/c/

or, to remove that final / as well:

$ echo "${p%/${p##*/c/}}"
/a/b/c/d/e/c

The standard parameter substitutions ${variable##pattern} and ${variable%pattern} removes the longest matching prefix string and the shortest matching suffix string respectively.

(To get /a/b/c, which you did not want, you would use # in place of ## in the "inner" substitution)

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.