Question

I have a Bash script:

var="
<Location /webdav/vendor1>
 DAV On
 AuthType Digest
 AuthName "rw"
 AuthUserFile /etc/password/digest-password
 Require user test123456
</Location>

<Location /webdav/limited/vendor1/demo>
 Dav On
 AuthType Digest
 AuthName "ro"
 AuthUserFile /etc/password/digest-password-test2
<LimitExcept GET HEAD OPTIONS PROPFIND>
deny from all 
</LimitExcept>
</Location>
"

sed -i -e "s/somestringX/${var}/g" change.txt

which returns error: sed: -e expression #1, char 9: unterminated `s' command

When $var is some single/multi-line string without special signs like /"'<>, everything works fine.

I guess that the problem is with the content of my $var, but I don't know what to do in order to make it work.

What could be the solution for this?

Was it helpful?

Solution

Sed can also use any character as a separator for the "s" command. Basically, sed takes whatever follows the "s" as the separator. So you could change your command to something like:

sed -i -e "s_somestringX_${var}_g" change.txt

You will want to ensure that the delimiter is not part of your target variable.

OTHER TIPS

You should replace all slashes with escaped slashes, being \/. That will do for most texts. If your text will however contain &, escape that, too. Any backslashes will have to be escaped as well, as \\

As your text doesn't seem to contain any ampersands or backslashes, this should do:

sed -i -e "s/somestringX/${var//\//\\\/}/g" change.txt

That seems rather complex, but we just replace / with \/. Bash can do this with ${string//substring/replacement}, but we have to escape the slashes and the backslashes.

you could try awk

awk -v v="$var" '{gsub("somestringX",v); print}' change.txt > newfile.txt

The only difference here is it would not modify the change.txt file in place as sed does with the -i option. It would redirect the result to newfile.txt

or if you want to do the same as sed -i

awk -v v="$var" '{gsub("somestringX",v); print}' change.txt > newfile.txt && mv newfile.txt change.txt
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top