Shell - 如何在sed命令中使用变量

时间:2017-03-31 13:54:51

标签: shell sed

在sed命令中使用变量时遇到问题。

我的剧本:

#!/bin/sh

#Declaracao de variaveis
dominio=$1
host=$2

#Configuração do Varnish
varnish_config=$(cat <<-END
if (req.http.host ~ "$dominio") {
        set req.backend_hint = $host;
        return (pass);
}
END
)

sed '51i\'"${varnish_config}" $PWD/teste

错误:

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

2 个答案:

答案 0 :(得分:0)

通过shell变量和sed(不适合多行替换)绕道而行是单调乏味的。在某个位置将文件插入另一个文件的方法是使用功能强大的编辑器,如ex

$ seq 5 > 5.txt
$ seq 10 > 10.txt
$ cat 10.txt
1
2
3
4
5
6
7
8
9
10
$ printf '6\nr 5.txt\nw\nq\n' | ex 10.txt
$ cat 10.txt
1
2
3
4
5
6
1
2
3
4
5
7
8
9
10

ex命令是:

6            set position to line 6
r 5.txt      read file 5.txt
w            write file
q            quit

答案 1 :(得分:0)

您需要在\n\\的每一行添加varnish_config。 shell会将此扩展为&#34; new line&#34;和\。如果在行尾将\ sed将下一行连接到当前行。

#!/bin/sh

#Declaracao de variaveis
dominio=$1
host=$2

#Configuração do Varnish
varnish_config=$(cat <<-END
if (req.http.host ~ "$dominio") {\n\\
        set req.backend_hint = $host;\n\\
        return (pass);\n\\
}
END
)

sed '51i\'"${varnish_config}" $PWD/teste
相关问题