我必须创建一个脚本来替换 apache 的 httpd.conf
中的几行文件。我有两个问题。首先,如何将多行保存到一个变量中?我试过了,但没用
replace="#ErrorLog "logs/error_log" '\n' ErrorLog "|<apache_location>/bin/rotatelogs <apache_location>/logs/error.%Y.%m.%d.log 86400"
'\n'
添加换行符不起作用。那么我的想法是像这样使用 sed(1):
sed -i "s#ErrorLog "logs/error_log"#$replace#g" $apache_httpd
我不知道这样行不行。
我能够用几行创建变量:
VAR="#ErrorLog \"logs/error_log\""
VAR="$VAR"$'\n'"ErrorLog \"|<apache_location>/bin/rotatelogs <apache_location>/logs/error.%Y.%m.%d.log 86400\""
replace="ErrorLog \"logs/error_log\""
现在问题出在 sed 上,我不得不使用不同的分隔符 ( http://backreference.org/2010/02/20/using-different-delimiters-in-sed/ )。但它一直在失败。
sed -i "s;$replace;$VAR;g" /root/daniel/scripts/test3/httpd.conf
sed:-e 表达式 #1,字符 54:未终止的“s”命令
最佳答案
据我所见,您的问题是,您没有正确转义变量赋值和 sed 单行中的双引号。
问题 1:
如果有的话,你必须转义引号:
kent$ r="foo\n\"bar\"\nbaz"
kent$ echo $r
foo
"bar"
baz
问题 2:
你也需要在你的 sed 行中使用转义引号:
例如:
kent$ cat file
keep the lines before
---
foo and "this"
---
keep the following lines
kent$ sed "s#foo and \"this\"#$r#" file
keep the lines before
---
foo
"bar"
baz
---
keep the following lines
关于linux - 用sed替换多行变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16134005/