-1
$ VAR="this is working well"
$ sed -i "s/$/,$VAR/" my.txt

$ VAR="this/got/error"
$ sed -i "s/$/,$VAR/" my.txt
sed: -e expression #1, char 12: unknown option to `s

I have to put various kind of strings to $VAR.

Sometimes $VAR is not working with sed. Bcoz of special character.

How can I solve this problem with sed or regular expression?

Thank u in advance.

S-K
  • 87
  • 5

2 Answers2

0

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.

bk2204
  • 64,793
  • 6
  • 84
  • 100
0

Whilst sed tutorials typically use / as the search/replace delimiters, you can use many other symbols as delimiters. For example s/one/two/ could also be written as s|one|two or as s#one#two.

So - to solve your particular problem, the solution is simple - use a different delimiter.

$ cat file.txt
1
2
3
4

$ VAR="this is working well"
$ sed  's/$/,'"$VAR"'/' file.txt
1,this is working well
2,this is working well
3,this is working well
4,this is working well

$ VAR="this/got/error"
$ sed  's|$|,'"$VAR"'|' file
1,this/got/error
2,this/got/error
3,this/got/error
4,this/got/error
$
fpmurphy
  • 2,464
  • 1
  • 18
  • 22