I thought i might throw out some simple examples of using regexes with ruby for when i forget
command = `mpstat -P ALL`
regex = /(?<NAME0>load)\s+average:\s+(?<NAME1>\S+),\s+(?<NAME2>\S+),\s+(?<NAME3>\S+)/x
result = command.match(regex)
# Print your regex
puts " #{result['NAME0']} #{result['NAME1']} #{result['NAME2']} #{result['NAME3']}"
#or
puts " #{result[1]} #{result[2]} #{result[3]} #{result[4]}"
annndd… something more complicated in context of something else
#!/usr/bin/env ruby
require "getopt/long"
require 'socket'
opt = Getopt::Long.getopts(
["--server", "-s", Getopt::REQUIRED],
["--port", "-p", Getopt::REQUIRED],
["--environment", "-e", Getopt::REQUIRED]
)
unless opt["s"] and opt["p"] and opt["e"]
unless opt["p"] =~ /\d+/
currentFile = File.basename(__FILE__)
puts "usage: ./#{currentFile} -s graphiteServer -p graphitePort -e siteEnvironment"
puts "usage: ./#{currentFile} -s someserver -p 2003 -e dev"
exit 1
end
end
statprefix = 'stats'
hostname = `hostname`.chomp
command = `mpstat -P ALL`
epoch = (Time.now.to_i).to_s
graphiteServer = opt["s"]
graphitePort = opt["p"]
siteEnv = opt["e"]
regexTitles = /(?<TITLEID>CPU\s.*)/x
partsTitle = command.match(regexTitles)
partsTitle = partsTitle['TITLEID'].split
regex = /(?<CPUID>all.*)/x
parts = command.match(regex)
parts = parts['CPUID'].split
hash = Hash[partsTitle.zip(parts)]
sock = TCPSocket.new(graphiteServer, graphitePort)
hash.each_pair do |title,value|
title = title.sub(/^\%/,"")
sock.puts "#{statprefix}.#{siteEnv}.#{hostname}.cpu.all.#{title} #{value} #{epoch}"
end
sock.close