2017-03-31 79 views
1

我在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' 

回答

0

您需要添加\n\\varnish_config每一行。 shell将这个扩展为“新行”并且\。如果在行尾将是\,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 
+0

谢谢,解决了我的问题:) –

+0

很确定这会在每个插入的行之后引入一个空行。只用''''''来换行就足够了。 –

+0

是的,但在文件中插入的文本将在一行中。 – komar

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