7

I'd like to know if there's a way to make multilple regexp replacements in bash with ${string//substring/replacement} or, possibly, what better solution exists.

I have a script to send updates to statusnet and friendika with curl. I sign petitions online, for instance, and am offered to tweet them, but would rather send to identica. I'm tired of pasting stuff and having to edit in terminal to escape @ and #, ! and ?. I'd like to regexp replace them in my script to automagically change

@repbunghole and @SenatorArsehat Stop farking around with #someship! Do you want me to come smack you? | http://someshort.url

to

\@repbunghole \@SenatorArsehat Stop farking around with \#someship\! Do you want me to come smack you\? \| http://someshort.url

I do not have strong sed or awk fu, but imagine they may offer solutions, and I don't know how to use sed without writing the variable to a file, reading the file and acting on it, then setting the var with var=$(cat file). Yes. I'm pretty new at this stuff. I'm not finding sufficient data with the above ${string//substring/replacement/} for multiple replacements. Running that X times to escape X different characters seems inefficient.

like

read -p "Enter a string: " a
b=${a//\@/\\\@}
c=${b//\#/\\\#}
d=${c//\!/\\\!}
e=${d//\?/\\\?}
f=${e//\"/\\\"}
g=${f//\'/\\\'}

etc., etc. works in the meantime, but it's ugly...

2 Answers 2

8

That's what character classes are for:

b=${a//[@#!?"']/\\\0}
Sign up to request clarification or add additional context in comments.

Comments

4

for "multiple regex replacement on variable in bash?"

both sed and awk can do it. e.g I want to replace

a->1
b->2
c->3

with sed:

kent$  v=abc
kent$  newV=$(sed -e's/a/1/; s/b/2/; s/c/3/' <<< $v)
kent$  echo $newV2
123

with awk:

kent$  v=abc
kent$  newV2=$(awk '{gsub(/a/,"1");gsub(/b/,"2");gsub(/c/,"3")}1' <<< $v)                                                                
kent$  echo $newV                                                        
123

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.