0

In bash programming, given a variable, say varA, that store a string containing # symbol. Let's assume varA contain this value: ASD# 1, I need to append a backslash \ at the front of #, so the output could have this: ASD\# 1. The following code is about there to achieve my objective, just that the string replacement doesn't seem to work and I'm not able to assign the output from sed command into another variable. Any sight on this?

varA="ASD# 1"
echo $(sed s/\#/\\#/g <<< ${varA})
3

You missing quote in your sed expression.

Try:

$ varA="ASD# 1"
$ echo "$(sed 's/#/\\#/g' <<< "${varA}")"
ASD\# 1
  • how can I assign the output to a variable? – huahsin68 Nov 18 '14 at 6:22
  • @huahsin68: simply varB="$(sed 's/#/\\#/g' <<< "${varA}")" – cuonglm Nov 18 '14 at 6:24
1

There is overhead to use sed just for one variable. In bash you can use ${varA/\#/\\\#}.

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.