Last active
February 26, 2018 19:25
-
-
Save gregmark/e5dc568ea8785d0df7c9e8a231739001 to your computer and use it in GitHub Desktop.
sort your IPs with perl
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/perl | |
##################################################################### | |
### | |
### sort_ips.pl | |
### ----------- | |
### | |
##################################################################### | |
use strict; | |
use warnings; | |
use Getopt::Long; | |
use File::Basename; | |
my $me = basename($0); | |
##################################################################### | |
### PREP | |
##################################################################### | |
### Options | |
my ($reverse, $help); | |
my $result = GetOptions ( | |
"r" => \$reverse, | |
"h" => \$help, | |
); | |
sub print_usage { | |
my $USAGE = <<EOF; | |
<command> | $me [-r] | |
command output with 1+ fields of IP, inclusive | |
-r print in reverse order | |
EOF | |
print $USAGE; exit 0; | |
} | |
&print_usage if $help; | |
### Arguments | |
# Look for arguments | |
my ($field, $sep) = @ARGV[0,1]; | |
# ARG 1: field to sort (DEFAULT = 1) | |
$field = 1 unless ( $field && $field =~ /^\d+$/ ); | |
$field--; | |
# ARG 2: field separator (DEFAULT = whitespace) | |
$sep = '\\s+' unless $sep; | |
my $sep_re = qr/$sep/; | |
##################################################################### | |
### MAIN | |
##################################################################### | |
# Pre-compile IP regex | |
my $ip_regex = qr/\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/; | |
# Collect unsorted data into array | |
my @unsorted; | |
while (defined (my $line = <STDIN>)) { | |
chomp $line; | |
next if $line =~ /^\s*$/; | |
next if $line !~ $ip_regex; | |
push @unsorted, $line; | |
} | |
# Make sorted array | |
my @sorted = | |
map { $_->[0] } | |
#sort { $a->[1] cmp $b->[1] } | |
sort { $b->[1] cmp $a->[1] } | |
map { [$_, sprintf("%03.f%03.f%03.f%03.f", (split(/\./, (split($sep_re, $_))[$field])))] } | |
@unsorted; | |
@sorted = reverse @sorted if $reverse; | |
# Output | |
foreach (@sorted) { print $_ . "\n" } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I know I got the regex from someone else. The rest is pretty elementary.