user7319905
user7319905

Reputation:

space issue using sed command

var=abc cde fgh ijk

I have ran below command

 sed -i '$s/}/,\n"filename":"'$var'/g"}/'

getting below error

sed: -e expression #1, char 32: unterminated `s' command

because "abc cde fgh ijk" having spaces inbetween the string value.

Expected output is to print : abc cde fgh ijk

Thanks

Upvotes: 1

Views: 1118

Answers (3)

terdon
terdon

Reputation: 3370

There are a few issues here. First, yes, the spaces are confusing sed since you are passing them unquoted. Then, you also have a syntax error in g}/. The syntax of the substitution operator is:

s/original/replacement/options

For example:

s/foo/bar/g

But you are using:

s/foo/bar/g"}/

In any case, unless you have multiple } on the last line of your file, the g is pointless.

So, depending on what you are actually trying to do, you want one of (UI have removed the -i to show the output, add it again to make the replacement modify the original file):

$ cat file 
foo
bar}
$ sed  '$s/}/,\n"filename":"'"$var\"\}/" file 
foo
bar,
"filename":"abc cde fgh ijk"}

Or

$ cat file
foo
bar}}}
$ sed  '$s/}/,\n"filename":"'"$var\"\}/g" file 
foo
bar,
"filename":"abc cde fgh ijk"},
"filename":"abc cde fgh ijk"},
"filename":"abc cde fgh ijk"}

Of course, a much simpler approach would be to have set var to hold the entire target replacement, quotes and all:

$ cat file
foo
bar}
$ var=',\n"filename":"abc cde fgh ijk"}'
$ sed "\$s/}/$var/" file 
foo
bar,
"filename":"abc cde fgh ijk"}

Note that now that we're using double quotes, the $ in the sed expression needs to be escaped.

Upvotes: 0

Mischa
Mischa

Reputation: 2298

Change $var to "$var". Otherwise the space in var is visible to bash as an arg separator, terminating the sed "program".

Upvotes: 1

VIPIN KUMAR
VIPIN KUMAR

Reputation: 3137

Try this -

$cat f
Hello vipin
$var="abc cde fgh ijk"
$sed "s/Hello/$var/g" f
abc cde fgh ijk vipin

Upvotes: 0

Related Questions