Remove superfluous slashes from a given path with bash

How can I get rid of unnecessary slashes in a given path?

Example:

p="/foo//////bar///hello/////world" 

I want:

 p="/foo/bar/hello/world" 
+7
source share
7 answers

Use readlink :

 p=$(readlink -m "/foo//////bar///hello/////world") 

Please note that this will lead to the canonization of symbolic links. If this is not what you want, use sed :

 p=$(echo "/foo//////bar///hello/////world" | sed s#//*#/#g) 
+19
source

Using pure bash:

 shopt -s extglob echo ${p//\/*(\/)/\/} 
+6
source

With realpath:

realpath -sm $p

Options:

  -m, --canonicalize-missing no components of the path need exist -s, --strip, --no-symlinks don't expand symlinks 
+2
source
  • Think about whether you need to do this. On Unix, specifying duplicate path separators (and even things like /foo/.//bar///hello/./world work fine.
  • You can use readlink -f , but this will also lead to canonicalization of symbolic links in this path, so the result will depend on your file system, and the provided path must actually exist, so this will not work for virtual paths.
0
source

This works with multiple delimiters and does not assume that this 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 lines containing ".."

0
source

your input:

 p="/foo//////bar///hello/////world" 

to remove irrelevant slashes:

 echo $p | tr -s / 

exit:

 /foo/bar/hello/world 
0
source

Thanks for answers. I know the way works fine. I just want this for optical reasons.

I found another solution: echo $p | replace '//' '' echo $p | replace '//' ''

-4
source

All Articles