简体   繁体   English

用sed替换整个短语

[英]Using sed to replace entire phrase

I'm using ShellScript to edit my bind dns configuration file, when add and remove zone references. 在添加和删除区域引用时,我正在使用ShellScript编辑我的bind dns配置文件。 Then in "master.conf" file we have this content: 然后在“master.conf”文件中我们有这样的内容:

...
...
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. 我希望使用“sed”将此条目“删除”到“mydomain.com”,但我无法为此编写正确的正则表达式。 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". 看到我们应该忽略括号之间的内容,并且这个块必须替换为“nothing”。 I tried some variations of this expression, but without success. 我尝试了这个表达式的一些变体,但没有成功。

Perhaps you could use awk? 也许你可以使用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 "};". 第二个字段中带有dom的行与仅包含“};”的行之间的范围为true。 next skips those lines. next跳过那些线。 The rest are printed. 其余的都打印出来了。

Use awk '...' file > tmp && mv tmp file to overwrite the original file. 使用awk '...' file > tmp && mv tmp file覆盖原始文件。

Try the below sed script it should work 尝试下面应该使用的sed脚本

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"

    };

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. 如果它不必是单行,您可以使用'grep'来获取行号,然后使用'sed'从行号中删除整个节。

See Delete specific line number(s) from a text file using sed? 请参阅使用sed从文本文件中删除特定行号?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM