Kartins
Kartins

Reputation: 3569

extract and replace a token in shell script

In a source code file, I need to change all the instances like

foo_bar('param')

to become

booch['param']=$param

Here, param is a token and it can vary. It can be anything.

i.e., in a file,

all the

foo_bar('xxx')

have to become

booch['xxx']=$xxx

and,

all the

foo_bar('yyy')

have to become

booch['yyy']=$yyy

and so on. I'm trying to do it by writing a shell script and using sed. But couldnt figure out how to do it. Hope my query is understandable. Thanks

Upvotes: 4

Views: 6262

Answers (2)

SiegeX
SiegeX

Reputation: 140417

sed "s/foo_bar('\([^']*\)')/booch['\1']=$\1/g" infile > outfile

Test

$ echo "foo_bar('xxx')" | sed "s/foo_bar('\(.*\)')/booch['\1']=$\1/"
booch['xxx']=$xxx

Upvotes: 6

jdonaldson
jdonaldson

Reputation: 198

Basically the same thing, using perl

cat yourfile.txt | perl -pe "s/(foo_bar)\(\s*('(\w*)')\s*\)/booch\[\$2\]=\\$\$3/" > youralteredfile.txt

Upvotes: 0

Related Questions