我如何在像rubk中的范围正则表达式中使用awk / start /,/ stop /
我想像这样做一个AWK风格的范围正则表达式:
awk ' /hoststatus/,/\}/' file
在AWK中,这将打印文件中两个模式之间的所有行:
hoststatus { host_name=myhost modified_attributes=0 check_command=check-host-alive check_period=24x7 notification_period=workhours check_interval=5.000000 retry_interval=1.000000 event_handler= }
我如何在Ruby中做到这一点?
额外奖励:你会怎么用Python做的?
这在AWK中非常强大,但我是Ruby的新手,不知道你是怎么做的。 在Python中,我也找不到解决方案。
ruby:
str = "drdxrdx hoststatus { host_name=myhost modified_attributes=0 check_command=check-host-alive check_period=24x7 notification_period=workhours check_interval=5.000000 retry_interval=1.000000 event_handler= }" str.each_line do |line| print line if line =~ /hoststatus/..line =~ /\}/ end
这是臭名昭着的触发器 。
用python传递多线和dotall标志来重新。 的? *之后使其变得非贪婪
>>> import re >>> with open('test.x') as f: ... print re.findall('^hoststatus.*?\n\}$', f.read(), re.DOTALL + re.MULTILINE)