1

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?

2 Answers2

2

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

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    The second solution works correctly for `p='/this/is/foo/the/path/to/afoo/bar/baz'`, unlike the first one. – choroba Jun 29 '15 at 15:43
  • Thanks @choroba, I corrected first one also for this case. – anubhava Jun 29 '15 at 15:45
  • The above "better would be to use" won't work as we are not checking for a / character just before word "foo". The correct command would be: echo "${p/\/$name/*/\/$name}" – AKS Jun 29 '15 at 15:57
  • 2
    I'd consider linking to http://mywiki.wooledge.org/BashFAQ/100 or http://wiki.bash-hackers.org/syntax/pe to give folks some guidance on the why/wherefore. – Charles Duffy Jun 29 '15 at 16:07
  • @CharlesDuffy great help. I also like: http://www.tldp.org/LDP/abs/html/string-manipulation.html (from Mendel Cooper) – AKS Jun 29 '15 at 16:11
  • 1
    @ArunSangal, I strongly advise against using the ABS as a source; it's poorly maintained and often uses bad practices in its examples. In the freenode #bash IRC channel, we're often trying to help people unlearn bad habits they got from the ABS. – Charles Duffy Jun 29 '15 at 16:12
0

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).

AKS
  • 16,482
  • 43
  • 166
  • 258