#! /usr/bin/env python import sys, re, os, tempfile def main(): """ %s [conversion type] [files] Converts line breaks of input file(s) regardless of input file type. The type of conversion is specified according to the first argument. Replace [files] with - to read stdin. Possible values for first argument: -d DOS -m Macintosh -u UNIX -n remove line breaks Other options: -h print this help message -v print version info """ version='$Id: lconv,v 1.2 2004/11/30 21:11:43 nghoffma Exp $' # match either \r or \n or both in any order anyending = re.compile(r'\r\n|\r|\n') leDict = {'d':'\r\n', 'u':'\n', 'm':'\r', 'n':''} msgDict = {'d':r'Converting %s to DOS format (\r\n)', 'u':r'Converting %s to UNIX format (\n)', 'm':r'Converting %s to Macintosh format (\r)', 'n':r'Removing line breaks from %s'} args = sys.argv[1:] try: option = args[0].lower().replace('-','') if option == 'v': sys.exit(version) elif option in 'h help'.split() or len(args) < 2: raise IndexError newending = leDict[option] except IndexError: sys.exit(main.__doc__ % os.path.split(sys.argv[0])[-1]) except KeyError: sys.exit('%s: bad conversion type (choose from d, m, u, n)' % args[0]) # special case for stdin if ''.join(args[1:]).strip() == '-': sys.stdout.write(anyending.sub(newending, sys.stdin.read())) else: for arg in args[1:]: tempname = tempfile.mktemp() try: infile = open(arg,'rb') outfile = open(tempname,'wb') # convert the line endings and write the result outfile.write(anyending.sub(newending, infile.read())) infile.close() outfile.close() os.rename(tempname, arg) except (IOError, OSError), msg: print msg continue print msgDict[option] % arg main()