Mark Harrison
Mark Harrison

Reputation: 304654

Bash: eliminating redundant path components?

How can I eliminate redundant components in a path?

For example, I would like to transform

/foo/../foo/bar

to

/foo/bar

Upvotes: 1

Views: 89

Answers (2)

anubhava
anubhava

Reputation: 785731

Using gnu realpath:

p='/foo/../foo/bar'

realpath -m "$p"

Output:

/foo/bar

As per realpath --help:

-m, --canonicalize-missing   no components of the path need exist

You can also use more commonly available readlink (thanks to @pjh):

readlink -m "$p"

Upvotes: 2

Muehlkreuz
Muehlkreuz

Reputation: 56

You might pipe through something like: sed 's-/../foo/-/-g' to replace up/down reference in path names.

Upvotes: 0

Related Questions