简体   繁体   中英

Sed in Bash script - replace error cause of variable content

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM