Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove unnecessary slashes from a given path with bash

Tags:

bash

path

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"
like image 828
casper Avatar asked Jan 09 '11 11:01

casper


People also ask

Does Linux use backslashes as path separators?

For a path to a local file on a windows machine, use backslash. For a path to a web resource or file located on a UNIX based machine (includes Macs, Linux), use a slash. The reason .

How do you escape a forward slash in Linux?

You need to escape the / as \/ . The escape ( \ ) preceding a character tells the shell to interpret that character literally. Show activity on this post. Escape it !

What is double slash in bash?

Thats a replacement pattern using bash parameter expansion. In ${f// /_} : The double slashes // are for replacing all occurrences of space with _ , if you put one slash / , only first space is going to be replaced. The space is there because you are replacing space (with underscore)


1 Answers

Use readlink:

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

Notice that this will canonicalize symbolic links. If that's not what you want, use sed:

p=$(echo "/foo//////bar///hello/////world" | sed s#//*#/#g)
like image 76
phihag Avatar answered Sep 20 '22 13:09

phihag