Friday, April 26, 2024
 Popular · Latest · Hot · Upcoming
2
rated 0 times [  2] [ 0]  / answers: 1 / hits: 21368  / 2 Years ago, mon, april 4, 2022, 10:47:27

I have a bash script for installing a web server on my Ubuntu server.



I'd like, in the /etc/apache2/apache2.conf, to replace



#ServerRoot "/etc/apache2"

#


by



#ServerRoot "/etc/apache2"
ServerName localhost

#


If I do



sed -i 's|#ServerRoot "/etc/apache2"|#ServerRoot "/etc/apache2"
ServerName localhost|' /etc/apache2/apache2.conf


it's working, but I'd like to include the blank line and the # after the #ServerRoot to avoid adding twice ServerName if the script is executed twice.



I tried



sed -i 's|#ServerRoot "/etc/apache2"

#|#ServerRoot "/etc/apache2"
ServerName localhost

#|' /etc/apache2/apache2.conf


But it's not working.


More From » bash

 Answers
0

How about




  1. search for #ServerRoot "/etc/apache2"

  2. if found, read and append the next line into sed's pattern space

  3. search the appended pattern space for an empty line after the newline, and substitute ServerName localhost for that



Putting that together,



sed -i '|#ServerRoot "/etc/apache2"| {N;s|
$|
ServerName localhost|}' /etc/apache2/apache2.conf


In case the 'empty' line actually contains whitespace, you could modify that to



sed -i '|#ServerRoot "/etc/apache2"| {N;s|
s*$|
ServerName localhost|}' /etc/apache2/apache2.conf

[#24308] Tuesday, April 5, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
motivengry

Total Points: 459
Total Questions: 112
Total Answers: 108

Location: Bonaire
Member since Sat, May 1, 2021
3 Years ago
;