LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Sed pattern matching (https://www.linuxquestions.org/questions/programming-9/sed-pattern-matching-475639/)

digitalbrutus 08-20-2006 12:02 PM

Sed pattern matching
 
I need to write a script to delete a <VirtualHost>...</VirtualHost> entry of a particular domain from httpd.conf using sed or awq or anything.

The entry will be some what like this

<VirtualHost 198.168.1.7>
ServerAlias something.com
ServerName www.something.com
DocumentRoot /www/docs/
</VirtualHost>

How can i remove such an entry from httpd.conf using a bash script that will search and find the entry for www.something.com and remove it.

I tried to do it with sed but the pattern was too complecated for me to understand and use. How do we match multiple line and remove those lines from a file using sed/awk. Plese help?

druuna 08-20-2006 01:37 PM

Hi,

There probably several ways to tackle this. Probably? Yes, I don't know if there are any empty lines between the VirtualHost entries. I assume (dangerous, I know) that there are.

If so, here are 2 (one useful, one for fun):

Using awk:
awk 'BEGIN { FS="\n" ; RS="" } $3 !~ /ServerName www.something.com/ { print $0, "\n" }' infile

Don't know the level of experience you have with awk, so here's a nutshell explanation.

BEGIN { FS="\n" ; RS="" } => This sets the Field (FS) and Record (RS) separator. Normally awk reads entries one line at the time, from left to right (RS="\n" and FS=" "), this makes sure that a one paragraph (empty line being the record separator) is read.

$3 !~ /ServerName www.something.com/ { print $0, "\n" } => If field 3 does not match 'ServerName www.something.com', print the paragraph.

If something isn't clear: Just ask.

And if you really, really want to do this with sed:
Code:

#!/bin/bash

sed -n '
# if an empty line, check the paragraph
/^$/ b para
# else add it to the hold buffer
H
# at end of file, check paragraph
$ b para
# now branch to end of script
b
# this is where a paragraph is checked for the pattern
: para
# return the entire paragraph
# into the pattern space
x
# look for the pattern, if there - delete, print all other paragraphs
/ServerName www.something.com/{d}
p
' $1

Hope this gets you going again.


All times are GMT -5. The time now is 07:07 PM.