Skip to content Skip to sidebar Skip to footer

How Do I Do A Range Regex In Ruby Like Awk /start/,/stop/

I want to do an AWK-style range regex like this: awk ' /hoststatus/,/\}/' file In AWK this would print all the lines between the two patterns in a file: hoststatus { host_name=myh

Solution 1:

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

This is the infamous flip-flop.


Solution 2:

with python passing in the multiline and dotall flags to re. The ? following the * makes it non-greedy

>>> import re
>>> with open('test.x') as f:
...     print re.findall('^hoststatus.*?\n\}$', f.read(), re.DOTALL + re.MULTILINE)

Post a Comment for "How Do I Do A Range Regex In Ruby Like Awk /start/,/stop/"