bash 在 sed 命令中使用变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18890235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using variables in a sed command
提问by Ozkan
I'm trying to add some text (a path) at the end of a line which is found by a sed command:
我正在尝试在 sed 命令找到的行的末尾添加一些文本(路径):
var="/folder1/folder2/folder3"
sed -i "/Begins with this text/s/$/$var/" filename
I know that double quotes are needed to use variables in a sed command but if I use the above command it gives me an error message saying:
我知道在 sed 命令中使用变量需要双引号,但是如果我使用上面的命令,它会给我一条错误消息:
expresssion #1, character 23: unknown option to `s
What am I doing wrong?
我究竟做错了什么?
回答by Barmar
Change the delimiter in the substitute command to something that won't appear in $var
, e.g.
将替换命令中的分隔符更改为不会出现在 中的内容$var
,例如
sed -i "/Begins with this text/s|$|$var|" filename
or escape the slashes in $var
:
或转义斜线$var
:
var="\/folder1\/folder2\/folder3"