Reputation: 6129
I would need to find a way in Bash (Linux shell in general) to get a base path from a given path. There are a few rules:
ABC
.ABC
contains a subdirectory which I don't know the name of. Below I call it XYZ
.Given this path
/some/absolute/path/foo/ABC/XYZ/bar/path/here
the result should be:
/some/absolute/path/foo/ABC/XYZ
The problem I'm having is due to XYZ
, because I don't know it, but need to keep it in the returned path.
Without the unknown XYZ
I could do this:
pwd | sed -e 's/ABC.*/ABC/'
Does anyone have a solution how I can solve this in Bash? Thanks!
Upvotes: 0
Views: 3942
Reputation: 360395
If you want to do it in pure Bash:
p='/some/absolute/path/foo/ABC/XYZ/bar/path/here'
m=ABC
t=${p##*$m/} # t=XYZ/bar/path/here
t=${t%%/*} # t=XYZ
new=${p%$m/*}$m/$t # new consists of "/some/absolute/path/foo/", "ABC", "/" and "XYZ"
Upvotes: 2