murrekatt
murrekatt

Reputation: 6129

How to get base path from path in shell script?

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:

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

Answers (2)

Dennis Williamson
Dennis Williamson

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

Erik
Erik

Reputation: 91300

sed -r 's,^(.*/ABC/[^/]+).*,\1,'

Upvotes: 2

Related Questions