Reputation: 341
in my tcsh script I have this
sed -i "s/^${y}$//g" $x
How do I get this to work? either I get no change or some error like Illegal Variable Name or Variable name must contain alphanumeric characters. Tried different combinations of "". '' within the sed . Example
sed 's/^'"${y}"'$//g' $x
Upvotes: 1
Views: 8492
Reputation: 263357
Expansion of variable names in double-quoted strings is tricky in tcsh. In your command:
sed -i "s/^${y}$//g" $x
the value of the shell or environment variable $y
should be expanded correctly, but the shell will try to expand $/
to the value of $/
, which as the error message says is an illegal variable name.
Your second command:
sed 's/^'"${y}"'$//g' $x
is almost correct; it's just missing the -i
argument to sed
.
This should work: . sed 's/^'"${y}"'$//g' $x
The {
and }
around y
aren't needed in this case, so you could write:
sed 's/^'"${y}"'$//g' $x
Or you can do it like this:
sed -i "s/^$y"'$'"//g" $x
This last version switches from double quotes to single quotes, and back to double, just around the $
character. It's a matter of emphasis, whether you want to use single quotes only around the $
that you don't want expanded, or to use double quotes only around $y
which you do want expanded.
Even more simply, you can escape a $
character in a double-quoted string by preceding it with \
(I think that may be specific to tcsh; the original csh might not have been able to do that). So I think this is the preferred approach -- assuming you have tcsh and not old-style csh:
sed -i "s/^$y\$//g" $x
I'm assuming that what you want to do is update the file named by $x
in place, deleting the string contained in $y
at the beginning of each line. That seems to be what you're trying to do, but I can't be certain.
Upvotes: 2