Error while matching End of line with $ in Sed command
I am currently applying the below command in csh
through a shell script.
sed -i "s/cb $i$/cb $i $cb/" */callback_events
Where:
-
$i
- Value of Variablei
-
$cb
- Value of Variable cb -
$
- To match the end of line
However, I am getting the following error with the above command.
Variable name must contain alphanumeric characters.
My current shell is /bin/csh
.
Solution 1:
You must escape the character $
when it is to stand for itself inside a string in doublequotes; otherwise the shell will think that it introduces a variable expansion, and will be unhappy if the character after it is not alphabetic or one of the special variables.
sed -i "s/cb $i"\$"/cb $i $cb/" */callback_events
There are two levels of character interpretation here.
-
First the shell reads the command and applies its rules. One of the rules is that inside doublequotes
$
introduces variable expansion. -
After the shell has finished the command looks like this:
sed -i s/cb <value-of-i>$/cb <value-of-i> <value-of-cb/ dir1/callback_events dir2/callback_events...
Note that the quotes are gone,
$i
and$cb
are replaced with their values, and\$
became just$
. Also*/callback_events
got replaced with a list of files. -
This is then passed to
sed
, which applies its rules. One of those rules is that a$
at the end of the search pattern means end-of-line.