shell - bash: get path to parent directory by name -


i'm trying path nearest parent directory named foo:

/this/is/the/path/to/foo/bar/baz  yields  /this/is/the/path/to/foo 

any idea how this?

using bash string manipulation:

p='/this/is/the/path/to/foo/bar/baz' name='foo'  r="${p%/$name/*}/$name"  echo "$r" /this/is/the/path/to/foo 

or better use:

p='/this/is/afoo/food/path/to/foo/bar/baz' echo "${p/\/$name\/*/\/$name}" /this/is/afoo/food/path/to/foo 

bash faq reference


Comments