I have a list of customers in a tab-delimited file, each with a corresponding set of IP ranges. However, I am uploading them to a database that does not accept a range in the third octet. That is, an IP of 24.53.241.150-185 is acceptable, but 24.53.150-185.241 is not.
In order to upload this list to the database, I need to separate IPs with a range in the third octet into separate IPs without ranges in the third octet (eg., 24.53.151.241, 24.53.152.241, etc.), and have this match up in the same format with its corresponding fields of "Customer" and "Admin Email".
How can I do this, using whatever tools would work? I'm flexible (Excel tools, Regex, Ruby, etc.).
The format of what I currently have:
What this needs to turn into (with the third octet separated into different rows):
I have figured this out using Ruby code, and applied it after saving the Excel file as a tab-delimited TXT file.
def expand_lines(line)
id, inst, ip = line.split("\t")
ip_compontents = ip.split('.')
if ip_compontents[2] =~ /(\d+)-(\d+)/
$1.to_i.upto($2.to_i).map do |i|
new_ip = [*ip_compontents[0..1], i, ip_compontents[3]].join('.')
[id, inst, new_ip]
end
else
[[id, inst, ip]]
end
end
if $0 == __FILE__
ext = File.extname(ARGV[0])
base = File.basename(ARGV[0], ext)
dir = File.dirname(ARGV[0])
outfile = File.join(dir, "#{base}_expanded#{ext}")
expanded = IO.read(ARGV[0]).split("\n").map {|l| expand_lines(l.chomp)}.flatten(1)
File.open(outfile, 'w') do |f|
f.puts expanded.map {|l| l.join("\t")}
end
end
This is one way to convert your string to a range of ips.
def convert_to_range(ip)
arr = ip.split('.')
ndx = arr.index { |s| s =~ /-/ }
f,l = arr[ndx].split('-')
(f..l).map { |s| [*arr.first(ndx), s, *arr[ndx+1..-1]].join('.') }
end
convert_to_range("24.53.94-105.241")
#=> ["24.53.94.241", "24.53.95.241", "24.53.96.241", "24.53.97.241",
# "24.53.98.241", "24.53.99.241", "24.53.100.241", "24.53.101.241",
# "24.53.102.241", "24.53.103.241", "24.53.104.241", "24.53.105.241"]
convert_to_range("24.53-58.105.241")
#=> ["24.53.105.241", "24.54.105.241", "24.55.105.241", "24.56.105.241",
# "24.57.105.241", "24.58.105.241"]
convert_to_range("24-26.58.105.241")
#=> ["24.58.105.241", "25.58.105.241", "26.58.105.241"]
convert_to_range("26.58.105.241-248")
#=> ["26.58.105.241", "26.58.105.242", "26.58.105.243", "26.58.105.244",
# "26.58.105.245", "26.58.105.246", "26.58.105.247", "26.58.105.248"]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.