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.


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

echo "$PWD///" | tr -s '/'
| improve this answer | |
  • 1
    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

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

$ shopt -s extglob
$ A="////qsd/////sdfgfg//qsd//////"
$ echo ${A//\/+(\/)/\/}
| 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:
| 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"

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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