Saturday, July 19, 2008

Different ways to skin a /etc/passwd file

Suppose we need to summarise how many users are using various shells. You can run a one-liner, AWK script or Python program. This exercise is just another opportunity for me to think in Python, that's all.

$ wc -l /etc/passwd
      74 /etc/passwd

$ cut -d: -f7 /etc/passwd | sort | uniq -c
  13
  14 /bin/bash
  38 /bin/sh
   1 /sbin/sh
   7 /usr/lib/rsh
   1 /usr/lib/uucp/uucico


$ awk -F: '
{
 ++s[$NF]
}
END {
 for ( i in s ) {
  printf("%4d %s\n",s[i],i)
 }
}' /etc/passwd
  13
  14 /bin/bash
  38 /bin/sh
   7 /usr/lib/rsh
   1 /usr/lib/uucp/uucico
   1 /sbin/sh


$ ./skin.py /etc/passwd
  13
   1 /sbin/sh
   7 /usr/lib/rsh
  14 /bin/bash
   1 /usr/lib/uucp/uucico
  38 /bin/sh


$ cat skin.py
#! /usr/sfw/bin/python

import sys

if len(sys.argv) != 2:
        print "Usage: ", sys.argv[0], "<colon_separated_file>"
        exit(1)


sdict={}
for line in open(sys.argv[1],"r"):
        shell = line.rstrip().split(":")[-1]
        try:
                sdict[shell] += 1
        except:
                sdict[shell] = 1

for i in sdict.keys():
        print "%4d %s" % (sdict[i],i)

I am about to start the OOP chapter in Learning Python, 3rd Edition and hope that I can program in OO in the future :-).

Labels: ,

0 Comments:

Post a Comment

<< Home