我有一个像这样的文本文件
....(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
..
如何获取PLAY RECAP和localhost之间的内容
并按照ec2-123.compute-1.amazonaws.com
的跟随值ok =?
输出像这个哈希?
{"ec2-123.compute-1.amazonaws.com" => 16,"ec2-456.compute-1.amazonaws.com" => 11,"ec2-766.compute-1.amazonaws.com" => 40,}
答案 0 :(得分:1)
要从整个文件中获取输入:
▶ input = input[/PLAY RECAP.*?^(.+?)^localhost/m, 1]
对结果进行哈希化:
▶ 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"
# }
按主机名排序(对于提醒,请使用WiktorStribiżew。)
input.scan(/(\S+) : ok=(\w+)/)
.to_h
.sort_by { |k, _| k[/(?<=ec2-)\d+/].to_i }
按ok
值排序(无论它意味着什么。)
input.scan(/(\S+) : ok=(\w+)/)
.to_h
.sort_by { |_, ok| ok.to_i }