2

I have to create a script to replace several lines in apache’s httpd.conf file. I have 2 problems. First, how I can save several lines into a single variable? I tried this, but it didn't work

replace="#ErrorLog "logs/error_log" '\n' ErrorLog "|<apache_location>/bin/rotatelogs <apache_location>/logs/error.%Y.%m.%d.log 86400"

The '\n' didn’t work to add a line break. Then my idea is use sed(1) like this:

sed -i "s#ErrorLog "logs/error_log"#$replace#g" $apache_httpd

I don’t know whether this will work.


I was able to create the variable with several lines:
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\""

Now the problem comes with the sed, I had to use a different delimiter (http://backreference.org/2010/02/20/using-different-delimiters-in-sed/). But it keep failing.
sed -i "s;$replace;$VAR;g" /root/daniel/scripts/test3/httpd.conf
sed: -e expression #1, char 54: unterminated `s' command

2
  • 3
    Just in general as a matter of simple but general principle, you will find that sed’s line-based processing can be a pain in the butt when dealing with anything that involves multiple lines. In these circumstances, and often in many others, you will find that swapping in perl for sed can make these things that were once frustratingly complex now perfectly straightforward and easy. So your Perl line would be something like perl -i.orig -ple 's/foo/bar/g' somefiles. Commented Apr 21, 2013 at 17:30
  • Thanks, but the script has a few hundred lines now :(. And I don't want to restart Commented Apr 21, 2013 at 20:05

1 Answer 1

1

From what I see here, your problem is, you didn't correctly escape the double-quote in your variable assignment and sed one-liner.

Question 1:

You have to escape the quotes if there is any:

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

Question 2:

you need escape quotes in your sed line too:

for example:

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.