Strip double dots from path in bash
I wonder how a regex could be used to simplify the double dots from a file path (the path may not actually exist)?
For example, change /my/path/to/.././my/./../../file.txt
to /my/file.txt
or path/./to/../../../file.txt
to ../file.txt
.
Is it possible to do this one command at a time in bash? (using sed
for example not complicated python or perl script)
edit : I came across this question but is realpath
not available on the computer I am using.
edit : In FJ's solution, I ended up creating the following regex, which works in more general cases (doesn't work if some path folder is named ....
):
sed -e 's|/\./|/|g' -e ':a' -e 's|\.\./\.\./|../..../|g' -e 's|^[^/]*/\.\.\/||' -e 't a' -e 's|/[^/]*/\.\.\/|/|' -e 't a' -e 's|\.\.\.\./|../|g' -e 't a'
Try the following:
sed -e 's|/\./|/|g' -e ':a' -e 's|/[^/]*/\.\./|/|' -e 't a'
Example:
$ echo '/my/path/to/.././my/./../../file.txt' |
sed -e 's|/\./|/|g' -e ':a' -e 's|/[^/]*/\.\./|/|' -e 't a'
/my/file.txt
Below is a description of the approach:
read line
replace all '/\./' in line with '/'
while there is a match of '/[^/]*/\.\./' {
replace first occurrence of '/[^/]*/\.\./' in line with '/'
}
output line