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

Suppose we declare

test="/this/isjust/atestvariable/for/stringoperation"

and we want to replace each instance of '/' with the colon ':'.

Then, I think this command should work:

echo ${test//\/:}

(as ${variable//pattern/string} replaces all matches of the pattern with the specified string )

But, on running echo ${test//\/:}, I get the output as

/this/isjust/atestvariable/for/stringoperation

Where I could be going wrong? Thank you for your help.

share|improve this question
up vote 5 down vote accepted

escape slash with backslash

echo ${test//\//:}
share|improve this answer

This:

${test//\/:}

would replace all instances (since double-slash // in the start) of /: with nothing (no second unescaped slash).

This:

${test/\//:}

Would replace the first instance (since a single slash as separator) of / (which was escaped) with :.

And this:

${test//\//:}

Should replace all matches of / with a :.

Example:

$ test="/this/isjust/atestvariable/:for/:stringoperation"
$ echo ${test//\/:}
/this/isjust/atestvariableforstringoperation
$ echo ${test/\//:}
:this/isjust/atestvariable/:for/:stringoperation
$ echo ${test//\//:}
:this:isjust:atestvariable::for::stringoperation
share|improve this answer

Your Answer

 
discard

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.