sed
does not have the concept of variables, and the variable you're using is being interpreted by the shell before sed
even sees it. Because of this, if you want to use some sort of variable that can handle arbitrary text, you need to use a different tool which can do this.
For example, you could do this using Perl:
$ perl -i 's/$/,$ENV{VAR}/g' my.txt
or you could do it using awk
and a temporary file:
$ awk '{ sub(/$/, "," ENVIRON["VAR"]); print }' my.txt > temp && mv temp my.txt
Note that using sed -i
, regardless of whether it has this problem or not, is not portable. On macOS, you must use sed -i ''
, but that syntax does not work on Linux. The perl -i
invocation is portable to all systems using Perl, as would be an equivalent technique using ruby -i
.