评论 out/delete 大量文件块

Comment out/delete blocks in large amount of files

我正在尝试编写一些可以处理包含文本块的 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”,以及 append/delete 块通过 sed/awk/perl,等等?

谢谢。

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

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

你可以test it here。我没有使用 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 '/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
这是它的工作原理
选择大括号内的块;继续附加到模式 space 直到找到右大括号;在模式 space 中搜索两个关键字;如果找到,则在模式 space 中的每个新行前面附加一个 # 并打印内容。清除模式 space 并重复证明