user2851669 user2851669 - 2 months ago 8
Bash Question

Replacing $a$ to &a using shell script

I want to replace all the occurrences of

$[a-z|A-Z|0-9]$
to
&[a-z|A-Z|0-9]
using shell script. For example,
$HELLO$
should become
&HELLO
.

I/P - $HELLO$
o/P - &HELLO


I tried using sed to replace the string.

sed -i -e 's/$*$/&/g filename

I/P - $HELLO$
O/P - &HELLO&


But I am unable to make sure that the last $ is replaced by a blank space and not
&

Answer

Using grouping and backreference::

$ sed 's/\$\([a-zA-Z0-9]*\)\$/\&\1/g' <<< '$HELLO$'
&HELLO
Comments