Brett
Brett

Reputation: 12017

How to use sed with a variable that needs to be escaped

I have a file, and I am trying to use bask to replace all the contents of a substring with a path.

I can use the command:

sed -i s/{WORKSPACE}/$MYVARIABLE/g /var/lib/jenkins/jobs/MY-JOB/workspace/config/params.ini

My config/params.ini looks like:

[folders]
folder1 = {WORKSPACE}/subfolder1
folder2 = {WORKSPACE}/subfolder2

however, when $MYVARIABLE is a path, it fails (containing slashes), the sed command fails with:

sed: -e expression #1, char 16: unknown option to `s'

When I run through it manually, I see that the $MYVARIABLE needs to have it's path-slashes escaped. How can I modify my sed command to incorporate an escaped version of $MYVARIABLE?

Upvotes: 1

Views: 116

Answers (2)

Tripp Kinetics
Tripp Kinetics

Reputation: 5459

There's nothing saying you have to use / as your delimiter. sed will use (almost) anything you stick in there. I have a tendency to use |, since that never (rarely?) appears in a path.

sridhar@century:~> export boong=FLEAK 
sridhar@century:~> echo $PATH | sed "s|/bin|/$boong|g"
~/FLEAK:/usr/local/FLEAK:/usr/local/sbin:/usr/local/games:/FLEAK:/sbin:/usr/FLEAK:/usr/sbin:/usr/games:/usr/lib/lightdm/lightdm:/home/oracle/app/oracle/product/12.1.0/server_1/FLEAK
sridhar@century:~> 

Using double-quotes will allow the shell to do the variable-substitution.

Upvotes: 1

jimm-cl
jimm-cl

Reputation: 5422

Just escape the $ sign, and use a different delimiter:

sed -i 's;{WORKSPACE};\$MYVARIABLE;g' your_file

Upvotes: 0

Related Questions