Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Is there a more Bashist way than echo "$PWD//" | sed -e 's#//\+#/#g' to replace repeating slashes with a single one?

Thanks Steven D, now there's a fully working function to find the longest common path of two or more paths: path_common.

share|improve this question
up vote 6 down vote accepted

Not a "Bash-only" answer, but perhaps useful:

echo "$PWD///" | tr -s '/'
share|improve this answer
The "squeeze" (-s) option to tr can be used on a range of characters, too: echo "aabbcc" | tr -s '[ac]' should yeild "abbc" – Bruce Ediger Apr 15 '11 at 20:35
+1, exactly what I was looking for – l0b0 Apr 19 '11 at 7:02

Possible in "pure bash", but only with extglob active.

$ shopt -s extglob
$ A="////qsd/////sdfgfg//qsd//////"
$ echo ${A//\/+(\/)/\/}
share|improve this answer
@Mat.. The replacement needs to be / (not \/) on my system... ???? – Peter.O Apr 19 '11 at 11:01
@fred.bear: both work here (bash 4.1.9(2)) – Mat Apr 19 '11 at 11:04
@Mat.. version 4.1.5(1) ... That must be it. thanks. – Peter.O Apr 19 '11 at 11:07

Bash only, by using a variable:

# code:
shopt -s extglob
echo "Original: $A"; 
echo "Result:   ${A//+(\/)//}"

# output:
Original: /home/myhome/Projects/Bob/build//
Result:   /home/myhome/Projects/Bob/build/
  • // = search and replace, keep searching and replacing

  • +(/) = match one or more of "/"

  • // = replace with, "/"

For a better visual example let's say that "z"s need to be squeezed to better see this without needing to escape the slash and not to have our search/replace confused with the infrastructure of ${VAR//pattern/string}:

# code:
shopt -s extglob
echo $A; 
echo ${A//+(z)/z}

# output:
share|improve this answer

UPDATE: Mat(+1) has got the right idea... my answer only works for odd numbers of "/"

it does not need "extglob" to be set.

var="$PWD///"; var="${var//\/\//}" ; echo "$var"

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.