How can I get rid of unnecessary slashes in a given path?
Example:
p=\"/foo//////bar///hello/////world\"
I want:
p=\"/f
/foo/.//bar///hello/./world
work just fine.readlink -f
, but this will also canonicalize the symlinks in that path, so the result depends on your filesystem and the path supplied must actually exist, so this won't work for virtual paths.With realpath:
realpath -sm $p
Parameters:
-m, --canonicalize-missing no components of the path need exist
-s, --strip, --no-symlinks don't expand symlinks
In zsh:
echo "${p:a}"
Works with non-existent paths, too.
This works with multiple separators and does not assume the given path should exist:
p=/foo///.//bar///foo1/bar1//foo2/./bar2;
echo $p | awk '{while(index($1,"/./")) gsub("/./","/"); while(index($1,"//"))
gsub("//","/"); print $1;}'
But does not simplify well strings containing ".."
Using pure Bash:
shopt -s extglob
echo ${p//\/*(\/)/\/}
Thanks for the replys. I know the path works fine. I just want this for optical reasons.
I found another solution: echo $p | replace '//' ''