linux - 用sed替换多行变量

标签 linux bash sed replace

我必须创建一个脚本来替换 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/

相关文章:

bash - 删除<某些命令> | netcat 通过 ssh 到后台

linux - 在启动时启动 tty.js

unix - Awk:使用包含标题的部分修改 csv

linux - 使用 bash 脚本更新 CRON

java - 启动时运行脚本

c - 如何在以下代码片段中替换 tmpnam() 的使用

bash - 是否可以在 bash 语法中使用变量?

linux - 如何只从变量中提取数字,我需要在这些数字之间留出空格?

linux - bash中间接引用数组的访问范围

shell - 使用 awk 或 sed 将十六进制转换为十进制