1

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.

rcsalvador
  • 81
  • 8
  • rather dangerous regex, since `(.*)` is going to suck up everything until the **LAST** `}` in the file. you could potentially nuke all the zones in the file. – Marc B Oct 02 '14 at 18:16
  • @Mark its only to next close bracket. I already change the text from question. Thanks from your note. – rcsalvador Oct 02 '14 at 18:25

3 Answers3

2

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.

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
  • Yes, I can use awk. But when I try your hint, the result output was the record entry. In my question I want **remove** this chunk of text from file, replacing it with '' (empty string). – rcsalvador Oct 02 '14 at 18:57
  • The whole point of the script is that it skips the entry (that's what `next` does). It works for me using your sample input. – Tom Fenech Oct 02 '14 at 20:03
  • Tom, your solution works fine too and was more elegant in my script. I was hasty with my previous comment. Tanks a lot. – rcsalvador Oct 02 '14 at 21:39
1

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"

    };
Ram
  • 1,115
  • 8
  • 20
  • Just one thing, there is a line-break after close bracket. Which character should I put into regex to remove this line-break? I tried \n and [\n] but don't removed behind line. – rcsalvador Oct 02 '14 at 20:49
0

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?

Community
  • 1
  • 1
jrel
  • 1