Regex 注释掉/删除大量文件中的块

Regex 注释掉/删除大量文件中的块,regex,sed,nagios,Regex,Sed,Nagios,我正在尝试编写一些可以处理包含一个文本块的Nagios配置文件的东西,并且可以添加到每行的开头,也可以删除该块。作为Nagios自身的一种大规模检查移除 例: 将需要更改为本标准或同等标准: define service { service_description Service 1 use Template 1 host_name Host 1 check

我正在尝试编写一些可以处理包含一个文本块的Nagios配置文件的东西,并且可以添加到每行的开头,也可以删除该块。作为Nagios自身的一种大规模检查移除

例:

将需要更改为本标准或同等标准:

define service {
        service_description     Service 1
        use                     Template 1
        host_name               Host 1
        check_command           Command A
}
#define service {
#        service_description     Service 2
#        use                     Template 1
#        host_name               Host 1
#        check_command           Command B
#}
define service {
        service_description     Service 3
        use                     Template 1
        host_name               Host 1
        check_command           Command C
}
是否有方法在定义服务{和}之间对块进行正则表达式匹配,并包含服务2或命令B,并通过sed/awk/perl等附加/删除块


谢谢。

这里有一个正则表达式,可以创建您想要的匹配项:

/define service\s\{.*(Service 2|Command B).*\}/s
你可以。我没有使用sed、awk或perl的经验,因此我不会尝试创建替换

sed '
# take each paragraph one by one
/define service {/,/}/{
# inside paragraphe, add each line (one at a time) in buffer
   H
# if not the end of paragraphe, delete the line (from output) (and cycle to next line)
   /}/!d
# empty current line (the last of paragraphe) and swap with the whole buffer
   s/.*//;x
# if it contain Service2 (and Command B on next line) goto to label comm
   /Service2/ b comm
   /Command B/ b comm
# goto label head (so no Service2 nor command b in paragraphe)
   b head
:comm
# comment each line of paragraphe (multiline with \n as new line)
   s/\n/&#/g
: head
# remove first character (a new line due to use of H and not h on first line)
   s/.//
   }
# default behaviour that print the content
 ' YourFile
自我评论的

sed-n'/定义服务{/,/}/{:1;n;/\}/!b1/命令B\|服务2/{s/\n/\n/g;s/^//g;p;d;b1};PDb 1}'文件名 这就是它的工作原理
拾取大括号内的块;一直追加到模式空间,直到找到右括号;在模式空间中搜索两个关键词;如果找到,则在模式空间中的每一新行前面追加一个,并打印内容。清除模式空间并重复验证

有。Awk或perl可能比sed更容易阅读:回复有点快,缺少要使用的上下文、参数和sed版本。如果没有特定选项,它在posix sed和GNU sed上都不起作用。这非常有效,谢谢!在sed中添加了-i,以将更改写入我的find循环中的每个文件。经过测试,这还会删除Nagios配置中的任何define host{块。这是为什么?@Myaá:你能提供一个例子吗?我不确定我是否理解了这个问题!
sed '
# take each paragraph one by one
/define service {/,/}/{
# inside paragraphe, add each line (one at a time) in buffer
   H
# if not the end of paragraphe, delete the line (from output) (and cycle to next line)
   /}/!d
# empty current line (the last of paragraphe) and swap with the whole buffer
   s/.*//;x
# if it contain Service2 (and Command B on next line) goto to label comm
   /Service2/ b comm
   /Command B/ b comm
# goto label head (so no Service2 nor command b in paragraphe)
   b head
:comm
# comment each line of paragraphe (multiline with \n as new line)
   s/\n/&#/g
: head
# remove first character (a new line due to use of H and not h on first line)
   s/.//
   }
# default behaviour that print the content
 ' YourFile