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

I want to write a script 'test.sh' that will take a user's input and replace all special characters with a '\' + the character. My script:

echo 'input='"$1"
arg=`echo "$1" | sed 's:[]\[\^\$\.\*\/]:\\&:g'`
echo 'modified input='"$arg"

My command works on the string 'xy', which does not have any special characters. I run this in my terminal:

test.sh xy

And I obtain:

modified input=xy

However, when I run this:

test.sh x.y

I get:

modified input=x&y

I don't understand why this script is not working. I expect to get:

modified input=x\.y

I think the problem lies in this sed command but I'm not sure where:

sed 's:[]\[\^\$\.\*\/]:\\&:g'
share|improve this question

I don't think you are capturing the group right. Try this?

sed 's:\([]\[\^\$\.\*\/]\):\\\1:g'

Edit: nevermind, I wasn't aware of the relevance of &. The problem is you need to extra escape the slashes in replacement because of the parsing and passing to sub shell.

sed 's:[]\[\^\$\.\*\/]:\\\\&:g'

Also, if you used $(command) instead of backticks, you don't need the extra \'s

share|improve this answer
Yes, if I add two more '\' as you did will work. But I don't see why they are needed. Is there a reference you can point me to understand this? Also, not sure what you mean regarding $(command) – drapkin11 Nov 7 '12 at 22:15
enclosing commands in backticks uses simple substitution - so the the command is parsed by the current shell. $(command) opens a subshell, so anything inside the parens runs as if on its own command line. See for more info: wiki.bash-hackers.org/syntax/expansion/cmdsubst – Drake Clarris Nov 8 '12 at 14:58

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.