【问题标题】:Replace multiple lines variable with sed用 sed 替换多行变量
【发布时间】:2013-04-21 17:22:31
【问题描述】:

我必须创建一个脚本来替换 apache 的 httpd.conf 文件中的几行。我有2个问题。首先,如何将多行保存到一个变量中?这个我试过了,还是不行

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 \"|&lt;apache_location&gt;/bin/rotatelogs &lt;apache_location&gt;/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 expression #1, char 54: unterminated `s' command

【问题讨论】:

  • 一般来说,作为一个简单但普遍的原则,你会发现在处理涉及多行的任何事情时,sed 的基于行的处理可能会让人头疼。在这些情况下,通常在许多其他情况下,您会发现将 perl 换成 sed 可以使这些曾经令人沮丧的复杂事情现在变得非常简单和容易。因此,您的 Perl 行将类似于 perl -i.orig -ple 's/foo/bar/g' somefiles
  • 谢谢,但脚本现在有几百行 :(。我不想重新启动

标签: linux bash sed replace


【解决方案1】:

从我在这里看到的情况来看,您的问题是,您没有正确转义变量赋值和 sed 单行中的双引号。

问题 1

如果有引号,您必须转义

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

问题 2

您的 sed 行中也需要 escape 引号:

例如:

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

【讨论】:

    猜你喜欢
    • 2014-11-20
    • 2011-10-04
    • 2019-03-24
    • 1970-01-01
    • 2011-12-02
    • 2021-11-20
    • 1970-01-01
    • 2016-10-06
    • 2010-11-16
    相关资源
    最近更新 更多