2013-04-21 113 views
2

我必须创建一个脚本来替换apache的httpd.conf文件中的几行。我有两个问题。首先,我如何将多行保存到一个变量中?我想这一点,但没有奏效用sed替换多行变量

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'命令

+3

只是一般般的简单,但总的原则问题,你会发现任何涉及多行打交道时的sed的基于行的处理可以是一个痛苦的对接。在这些情况下,并且通常在许多其他情况下,您会发现在sel中交换sed可以使这些曾经令人沮丧地复杂的事情变得非常简单和容易。所以你的Perl行会像'perl -i.orig -ple's/foo/bar/g'somefiles'。 – tchrist 2013-04-21 17:30:23

+0

谢谢,但脚本现在有几百行:(而且我不想重新启动 – radicaled 2013-04-21 20:05:26

回答

1

从我看到这里,你的问题是,你没有正确地转义双引号中的变量赋值和sed单线。

问题1

你必须逃生引号,如果有任何:

kent$ r="foo\n\"bar\"\nbaz" 
kent$ echo $r 
foo 
"bar" 
baz 

问题2

你需要逃生在引号您sed line too:

例如:

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