Ignore dollar value in sed

Hi Guys,

I need to replace the string based on specific value by keeping dollar sign

input=$1
var=$(echo "@code_temp_table_$value_table"| sed -r "s/\@code/${input}/;s/(nz|sa)_\$value_/\$value1_\1_/" )

Expected

if
input=nz,sa
then
nz_temp_table_$value1_table
else
if any other input for eg input=us
us_temp_table_$value_table

Hi, try:

echo '@code_temp_table_$value_table'| sed -r "s/\@code/${input}/; /^(nz|sa)_/s/\\\$value_/\$value1_/"

Within double quotes, you need to escape both the \ and the $ character, to protect them from the shell, so that sed "sees" \$ in the regex part of the s command.

Also, you need single quotes for the echo statement, or escape the $ sign :

echo "@code_temp_table_\$value_table"

I am getting below error

bash-3.2$ echo $input
nz
bash-3.2$ echo '@code_temp_table_$value_table'| sed -r "s/\@code/${input}/; /^(nz|sa)_/s/\\\$value_/\$value1_/"
sed: illegal option -- r
usage: sed script [-Ealn] [-i extension] [file ...]
       sed [-Ealn] [-i extension] [-e script] ... [-f script_file] ... [file ...]
bash-3.2$ 

Hello Rohit, the -r option as specified by the OP is GNU sed, regular sed can not do alternation ( nz|sa )

With BSD sed (like on MacOS) you can try sed -E

Try \| for the alternation ... but don't forget to escape the parentheses as well.

EDIT: Hoppla - that seems to be GNU as well ...

Indeed \| is a GNU extension to Basic Regular Expressions ( BRE ), as are \? and \+ . But I do not see a use for them, since GNU utilities also support at least Extended Regular Expressions (ERE) which supports | ? and + , with the -E option for GNU grep (as with any grep) and the -r option for sed.

Standard sed uses BRE and does not understand ERE, nor the GNU extensions to BRE.
BSD sed has a -E option for ERE, but does not understand the GNU extensions to BRE
Any standard grep does support -E for ERE, but not the GNU extensions to BRE.

The drawback of ERE is that officially it does not support back reference, but the GNU and BSD versions do.

2 Likes