0

We have couple of scripts where we want to replace variable evaluation method from $VAR_NAME to ${VAR_NAME}
This is required so that scripts will have uniform method for variable evaluation

I am thinking of using sed for the same, I wrote sample command which looks like follows,

echo "\$VAR_NAME" | sed 's/^$[_a-zA-Z0-9]*/${&}/g'

output for the same is

${$VAR_NAME}

Now i don't want $ inside {}, how can i remove it?
Any better suggestions for accomplishing this task?

EDIT Following command works

echo "\$VAR_NAME" | sed -r 's/\$([_a-zA-Z]+)/${\1}/g'

EDIT1
I used following command to do replacement in script file

sed -i -r 's:\$([_a-zA-Z0-9]+):${\1}:g' <ScriptName>
ART
  • 1,509
  • 3
  • 29
  • 47

1 Answers1

1

Since the first part of your sed command searches for the $ and VAR_NAME, the whole $VAR_NAME part will be put inside the ${} wrapper.

You could search for the $ part with a lookbehind in your regular expression, so that you end up ending the sed call with /{&}/g as the $ will be to the left of your matched expression.

http://www.regular-expressions.info/lookaround.html
http://www.perlmonks.org/?node_id=518444

I don't think sed supports this kind of regular expression, but you can make a command that begins perl -pe instead. I believe the following perl command may do what you want.

perl -p -e 's/(?<=\$)[_a-zA-Z0-9]*/{$&}/g'

PCRE Regex to SED

Community
  • 1
  • 1
John M
  • 11
  • 2