rcsalvador
rcsalvador

Reputation: 79

Using sed to replace entire phrase

I'm using ShellScript to edit my bind dns configuration file, when add and remove zone references. Then in "master.conf" file we have this content:

...
...
zone "mydomain.com" {
   type master; 
   file "/var/zones/m/mydomain.com"
};
...
...

I want "remove" this entry to "mydomain.com" using "sed", but I could'n write a correct regex to this. The expression must use variable domain name and search until next close bracket and semicolon, something like this:

DOMAIN_NAME="mydomain.com"
sed -i.bak -r 's/^zone "'$DOMAIN_NAME'" \{(.*)\};$//g' /var/zones/master.conf

See that we should ignore the content between brackets, and this chunk have to replaced with "nothing". I tried some variations of this expression, but without success.

Upvotes: 1

Views: 169

Answers (3)

Ram
Ram

Reputation: 1115

Try the below sed script it should work

Code:

sed -i '/"mydomain.com" [{]/{
:loop
N
s/[}][;]/&/
t end
b loop
:end
d
}' master.conf

Input:

zone "myd.com" {
   type master;
   file "/var/zones/m/mydomain.com"

};
zone "mydomain.com" {
   type master;
   file "/var/zones/m/mydomain.com"
};

Output:

zone "myd.com" {
       type master;
       file "/var/zones/m/mydomain.com"

    };

Upvotes: 1

Tom Fenech
Tom Fenech

Reputation: 74685

Perhaps you could use awk?

awk -v dom="mydomain.com" '$2 ~ dom, /^};$/ {next}1' file

The , is the range operator. The range is true between the lines with dom in the second field and the line that only contains "};". next skips those lines. The rest are printed.

Use awk '...' file > tmp && mv tmp file to overwrite the original file.

Upvotes: 2

jrel
jrel

Reputation: 1

If it doesn't have to be a one liner, you can use 'grep' to get the line numbers, and then use 'sed' to delete the entire stanza from the line numbers.

See Delete specific line number(s) from a text file using sed?

Upvotes: 0

Related Questions