#!/usr/bin/env python # # Copyright (c) 2000 Dominic Mitchell. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # """Sort a file with ip addresses in a column.""" __rcsid__ = "@(#) $Id: sortips.py,v 1.1 2001/07/26 22:52:32 dom Exp $" __version__ = "$Revision: 1.1 $"[11:-2] import os,sys import string import getopt import fileinput def usage(): me = os.path.basename(sys.argv[0]) sys.stderr.write("usage: %s [-c col] [file ...]") sys.exit(1) def main(files, col=0): """Sort by ip address in column col, to stdout.""" lines = {} for line in fileinput.input(args): line = string.rstrip(line) try: ip = string.split(line)[col] ip = string.split(ip, '.') ip = map(int, ip) # Convert string -> int. # Must make it a long here... num = ip[0] *256*256*256L + ip[1]*256*256L + ip[2]*256L + ip[3] except ValueError: num = 0 if not lines.has_key(num): lines[num] = [] lines[num].append(line) nums = lines.keys() nums.sort() for n in nums: for l in lines[n]: print l return if __name__ == '__main__': col=0 try: opts,args = getopt.getopt(sys.argv[1:], 'c:') except getopt.error: usage for o, a in opts: if o == '-c': col=int(a) main(args, col) # vim: set ai et sw=4 :