Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Shell-如何在sed命令中使用变量_Shell_Sed - Fatal编程技术网

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

Shell-如何在sed命令中使用变量,shell,sed,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 '51

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

通过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

通过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

您需要将
\n\\
添加到
varnish\u 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
#/垃圾箱/垃圾箱
#变量声明
多米尼奥=1美元
主机=$2
#Configuração do清漆

varnish\u config=$(cat您需要将
\n\\\
添加到
varnish\u 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
!/bin/sh
#变量声明
多米尼奥=1美元
主机=$2
#Configuração do清漆

清漆配置=$(cat非常确定这会在插入的每一行之后引入一个空行。只需使用
\
转义换行符就足够了。是的,但是文件中插入的文本将在一行中。Mac OSX不支持该sed命令。您能提供解决方案吗?非常确定这会在插入的每一行之后引入一个空行。)ted行。只需使用
\
转义换行符就足够了。是的,但是文件中插入的文本将在一行中。Mac OSX不支持该sed命令。您能提供解决方案吗?