user578895
user578895

Reputation:

bash: get path to parent directory by name

I'm trying to get the path to the nearest parent directory named foo:

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

yields

/this/is/the/path/to/foo

Any idea how I do this?

Upvotes: 1

Views: 661

Answers (2)

anubhava
anubhava

Reputation: 785128

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 would be to 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

Upvotes: 2

AKS
AKS

Reputation: 17326

Try this: This operation (using % sign) will remove anything after foo word (if it's in a variable var from the right side) then suffix it with foo.

echo ${var%/foo/*}foo

or

echo ${var/\/foo\/*/\/foo}

Removing foo (at last) from the above command will give the parent folder of first occurrence of foo folder. Including foo will give you the first foo folder as the parent.

PS: If there's no "/foo/" folder in the path, then, the above echo command will output whatever is the value of given path (i.e. $var as it's) aka it'll output a wrong output for your purpose OR it may work correctly only in case the given path i.e. $var is /foo).

Upvotes: 0

Related Questions