Newer
Older
tgrepcsv / tgrepcsv.py
tundra on 18 Sep 2012 5 KB Updated usage screen.
#!/usr/bin/env python
# tgrepcsv.py - Search .csv File And Print Matching Lines
# Copyright (c) 2012 TundraWare Inc., Des Plaines, IL 60018 USA
# All Rights Reserved. For Terms Of Use See: tgrepcsv-license.txt
# For Program Updates See: http://www.tundraware.com/Software/tgrepcsv
# $Id: tgrepcsv.py,v 1.103 2012/09/18 15:29:42 tundra Exp $

# Embed the source control ID string for use by program

CVSID='$Id: tgrepcsv.py,v 1.103 2012/09/18 15:29:42 tundra Exp $'

#####
# Program Information
#####

PROGNAME = "tgrepcsv.py"
PROGENV  = "tgrepcsv".upper()
VERSION  = CVSID.split()[2]
PROGVER  = PROGNAME + " " + VERSION + " - Search .csv File And Print Matching Lines"


#####
# Copyright Information
#####

COPYRIGHT    = "Copyright (c) 2012 TundraWare Inc., Des Plaines, IL 60018 USA"

#####
# List Of All Legal Options - Update This When You Add More!!!!
#####

OPTIONSLIST = '-c:hv'


#----------------------------------------------------------#
#            Variables User Might Change                   #
#----------------------------------------------------------#



#------------------- Nothing Below Here Should Need Changing ------------------#


#----------------------------------------------------------#
#                       Imports                            #
#----------------------------------------------------------#

import csv
import getopt
import os
import sys


#----------------------------------------------------------#
#                 Aliases & Redefinitions                  #
#----------------------------------------------------------#



#----------------------------------------------------------#
#                Constants & Literals                      #
#----------------------------------------------------------#



#####
# Constants
#####

COLUMNWIDTH = 16
MINCOL      = 8

#####
# Literals
#####



#----------------------------------------------------------#
#              Prompts, & Application Strings              #
#----------------------------------------------------------#


#####
# Error Messages
#####

eBADARG      =  "Invalid command line: %s!"
eERROR       =  "ERROR"
eFEWARGS     =  "Too few commmand line arguments!"
eMINCOL      =  "Minimum column width is %s!" % MINCOL
eNOTINTEGER  =  "%s is not an integer!"

#####
# Usage Prompts
#####

uTable = [PROGVER,
          "usage:  " + PROGNAME + " [-c # -hv] csvfile pattern pattern ...",
          "   where,",
          "          -c #     column width (default: 16)",
          "          -h       print this help information",
          "          -v       print detailed version information",
          ]


#----------------------------------------------------------#
#          Global Variables & Data Structures              #
#----------------------------------------------------------#


#--------------------------- Code Begins Here ---------------------------------#


#----------------------------------------------------------#
#             Object Base Class Definitions                #
#----------------------------------------------------------#

    

#----------------------------------------------------------#
#             Supporting Function Definitions              #
#----------------------------------------------------------#


def ColumnPad(list, padchar=" ", padwidth=COLUMNWIDTH):

    retval = ""
    for l in list:
        l = str(l[:padwidth-1])
        retval += l + ((padwidth - len(l)) * padchar)

    return retval.strip()

# End of 'ColumnPad()'


#####
# Print An Error Message
#####

def ErrorMsg(emsg):
    PrintStderr(PROGNAME + " " + eERROR + ": " + emsg)

# End of 'ErrorMsg()'


#####
# Print To stderr
#####

def PrintStderr(msg, trailing="\n"):
    sys.stderr.write(msg + trailing)

# End of 'PrintStderr()'


#####
# Print To stdout
#####

def PrintStdout(msg, trailing="\n"):
    sys.stdout.write(msg + trailing)

# End of 'PrintStdout'


#####
# Print Usage Information
#####

def Usage():
    for line in uTable:
        PrintStdout(line)

# End of 'Usage()'


#----------------------------------------------------------#
#                    Program Entry Point                   #
#----------------------------------------------------------#

# Command line processing - Process any options set in the
# environment first, and then those given on the command line

OPTIONS = sys.argv[1:]
envopt = os.getenv(PROGENV)
if envopt:
    OPTIONS = envopt.split() + OPTIONS

try:
    opts, args = getopt.getopt(OPTIONS, OPTIONSLIST)

except getopt.GetoptError, (errmsg, badarg):

    ErrorMsg(eBADARG % errmsg)
    sys.exit(1)

for opt, val in opts:

    if opt == "-c":
        try:
            COLUMNWIDTH = int(val)

        except:
            ErrorMsg(eNOTINTEGER % val)
            sys.exit(1)

        if COLUMNWIDTH < MINCOL:
            ErrorMsg(eMINCOL)
            sys.exit(1)
        
    if opt == "-h":
        Usage()
        sys.exit(0)

    if opt == "-v":
        PrintStdout(CVSID)
        sys.exit(0)


# Check and parse command line args

if len(args) < 2:

    ErrorMsg(eFEWARGS)
    sys.exit(1)

CSVFile  = args[0]
Patterns = args[1:]


# Read the file into a local list

content = []
with open(CSVFile, 'rb') as f:
    
    reader = csv.reader(f)
    for row in reader:
        content.append(row)


# Output lines matching any of the expressions

for row in content:

    line = ColumnPad(row, padwidth=COLUMNWIDTH)

    match = False
    for pattern in Patterns:
        if pattern in line:
            match = True

    if match:
        PrintStdout(line)