Shiyang Wang Shiyang Wang - 3 months ago 8
Ruby Question

ruby how to match a substring

I have a text file like this

....(omission)
ec2-123.compute-1.amazonaws.com : ok=333

....

PLAY RECAP *********************************************************************
ec2-123.compute-1.amazonaws.com : ok=16 changed=2 unreachable=0 failed=0
ec2-456.compute-1.amazonaws.com : ok=11 changed=0 unreachable=0 failed=0
ec2-766.compute-1.amazonaws.com : ok=40 changed=15 unreachable=0 failed=0
localhost : ok=0 changed=0 unreachable=0 failed=0

...(omission)
ec2-123.compute-1.amazonaws.com : ok=1231
..


How to get the content between PLAY RECAP and localhost
and sort the host name like
ec2-123.compute-1.amazonaws.com
by it's follow value ok=?

output like this hash?

{"ec2-123.compute-1.amazonaws.com" => 16,"ec2-456.compute-1.amazonaws.com" => 11,"ec2-766.compute-1.amazonaws.com" => 40,}

Answer

To get an input out of the whole file:

▶ input = input[/PLAY RECAP.*?^(.+?)^localhost/m, 1]

To hashify the result:

▶ input.scan(/(\S+) : ok=(\w+)/).to_h
#⇒ {
#  "ec2-123.compute-1.amazonaws.com" => "16",
#  "ec2-456.compute-1.amazonaws.com" => "11",
#  "ec2-766.compute-1.amazonaws.com" => "40"
# }

To sort by host name (thx Wiktor Stribiżew for the reminder.)

input.scan(/(\S+) : ok=(\w+)/)
     .to_h
     .sort_by { |k, _| k[/(?<=ec2-)\d+/].to_i }

To sort by ok value (whatever it means.)

input.scan(/(\S+) : ok=(\w+)/)
     .to_h
     .sort_by { |_, ok| ok.to_i }
Comments