Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple regex replacement on variable in bash?

Tags:

regex

bash

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...

like image 886
tonybaldwin Avatar asked Sep 28 '11 15:09

tonybaldwin


2 Answers

That's what character classes are for:

b=${a//[@#!?"']/\\\0}
like image 62
Tim Pietzcker Avatar answered Oct 17 '22 14:10

Tim Pietzcker


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
like image 29
Kent Avatar answered Oct 17 '22 14:10

Kent