Add to Technorati Favorites
Welcome to ThePowerShellGuy.com Sign in | Join | Help

Sorting IP addresses, PowerShell vs AWK

 

A question was asked in the PowerShell Newsgroup how to sort IP addresses with an AWK example for the same task given

Keith Hill made a blogpost about the same Newsgroup Post using .NET here :  Sorting IP addresses the PowerShell way.

but I also liked that even using text parsing the resulting PoSH version ( after 20 NG posts ) is 1/2 shorter then the AWK one was :

AWK

cat ips | awk -F. '{printf("%03d.%03d.%03d.%03d\n", $1,$2,$3,$4)};' | sort -n -t "." | awk -F. '{printf("%d.%d.%d.%d\n", $1,$2,$3,$4)};'

PoSH ( *edit* sorry made a mistake not a valid solution )

gc ips|sort{"{0:d3}.{1:d3}.{2:d3}.{3:d3}"-f@($_.split('.'))}

*edit* as pointed out in the NG tread I made a mistake, but just when I did want to post a 49 char solution to save my face, I did see Dreeschkind already came up with a 47 character solution :

POSH :

gc ips|sort{$_.split('.')|%{'{0:d3}'-f[int]$_}}

*edit 06/26 * did think of aternate padding method just add a 1000, bringing length to 37

gc ips|sort{$_.split(".")|%{1000+$_}} 

PoSH> 'gc ips|sort{$_.split(".")|%{1000+$_}}'.length
37

Kiron got it to 36 using scientific notation, 

gc ips|sort{$_.split(".")|%{1e3+$_}}

Ok, think we reached the limit here, anyone less ? 

enjoy,

Greetings /\/\o\/\/

Published Sunday, June 24, 2007 6:43 AM by MoW
Filed under: ,

Comments

No Comments
Anonymous comments are disabled