Last active
October 12, 2016 03:56
-
-
Save ashmckenzie/7658fc698093fdbbe14e069b9bdc7139 to your computer and use it in GitHub Desktop.
Sort a set of scrambled hostnames in the format of <app><#>.<location>.<domain>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
class Location | |
attr_reader :name, :name_only, :number | |
def initialize(name) | |
@name = name | |
match = name.match(/(^[a-z]+)(\d+)?/) | |
@name_only = match[1] | |
@number = match[2].to_i | |
end | |
end | |
class Hostname | |
attr_reader :name, :name_only, :number, :location | |
def initialize(name) | |
@name = name | |
match = name.match(/(^[a-z]+)(\d+)?/) | |
@name_only = match[1] | |
@number = match[2].to_i | |
@location = Location.new(name.split('.')[1]) | |
end | |
end | |
class LocationsAndHosts | |
def initialize(handle) | |
@handle = handle | |
end | |
def display | |
sort_locations(locations).each do |location_and_hostnames| | |
location, data = location_and_hostnames | |
puts "%s\n%s\n" % [ location, '-' * location.length ] | |
sort_hostnames(data[:hostnames]).each { |h| puts h.name } | |
puts | |
end | |
end | |
private | |
attr_reader :handle | |
def locations | |
handle.each_with_object({}) do |line, locations| | |
hostname = Hostname.new(line.chomp) | |
locations[hostname.location.name] ||= { location: hostname.location, hostnames: [] } | |
locations[hostname.location.name][:hostnames] << hostname | |
end | |
end | |
def sort_locations(data) | |
data.sort do |x, y| | |
x = x[1][:location] | |
y = y[1][:location] | |
r = x.name_only <=> y.name_only | |
(r != 0) ? r : x.number.to_i <=> y.number.to_i | |
end.to_h | |
end | |
def sort_hostnames(data) | |
data.sort do |x, y| | |
r = x.name_only <=> y.name_only | |
(r != 0) ? r : x.number.to_i <=> y.number.to_i | |
end | |
end | |
end | |
LocationsAndHosts.new(ARGF).display |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great for using with
knife search
:knife search "<query>" -i | sort_hostname.rb