如何将sed与需要转义的变量一起使用

时间:2021-05-04 00:38:51

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

我有一个文件,我正在尝试使用bask用路径替换子字符串的所有内容。

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:

我的config / params.ini看起来像:

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

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

但是,当$ MYVARIABLE是路径时,它失败(包含斜杠),sed命令失败:

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?

当我手动运行它时,我发现$ MYVARIABLE需要让它的路径斜线转义。如何修改我的sed命令以合并$ MYVARIABLE的转义版本?

2 个解决方案

#1


1  

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.

没有什么可以说你必须使用/作为你的分隔符。 sed将使用(几乎)你坚持的任何东西。我倾向于使用|,因为从来没有(很少?)出现在路径中。

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.

使用双引号将允许shell执行变量替换。

#2


0  

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

只需转义$符号,并使用不同的分隔符:

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

#1


1  

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.

没有什么可以说你必须使用/作为你的分隔符。 sed将使用(几乎)你坚持的任何东西。我倾向于使用|,因为从来没有(很少?)出现在路径中。

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.

使用双引号将允许shell执行变量替换。

#2


0  

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

只需转义$符号,并使用不同的分隔符:

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