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

时间:2015-05-20 18:16:28

标签: regex sed nagios

我正在尝试编写可以处理包含文本块的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
}

需要更改为此(或等效):

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
}

有没有办法让正则表达式匹配“define service {”和“}”之间的块,并包含“Service 2”或“Command”B“,并通过sed / awk / perl追加/删除块,等?

感谢。

3 个答案:

答案 0 :(得分:0)

这是一个创建所需匹配的正则表达式:

/define service\s\{.*(Service 2|Command B).*\}/s

你可以test it here。我没有使用sed,awk或perl的经验,因此我不会尝试创建替代品。

答案 1 :(得分:0)

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

自评论

答案 2 :(得分:0)

sed -n '/define service {/,/}/{:1;N;/\}/!b 1;/Command B\|Service 2/{s/\n/\n#/g;s/^/#/g;p;d;b 1};p;d;b 1}' file_name
这是它的工作方式
选择大括号内的块;保持追加到模式空间直到找到右大括号;在模式空间中搜索两个关键词;如果找到,则在模式空间中的每个新行前面附加一个#并打印内容。清除模式空间并重复证明