Click to See Complete Forum and Search --> : Well, I'm bored.


jemfinch
03-28-2001, 04:33 AM
So here's another tool. Because of a bug in python 2.0, you'll have to wait until 2.1 comes out (I developed this with the beta, as you can tell from the first line) for this to actually work.

I wrote this so I could stop using perl -[pn]i -e and grep so often.


#!/usr/experimental/bin/python2.1

import re
import sys
import string
import getopt
import fileinput

inplace = 0
regexps = []
# perldoc perlre for an explanation of "(?<!", the "negative lookbehind
# assertion." Basically, this is used to split on regexps that *aren't*
# escaped with a backslash.
splitre = re.compile(r'(?<!\\)/')

USAGE = """
-i : In-place file editing.
-m/regexp/flags : Print only lines that match regexp.
-M/regexp/flags : Print only lines that don't match regexp.
-s/findre/replacement/flags : Replace findre with replacement, print result.

flags can be any of the following:
i : ignore case in the regexp.
L : use locale settings for \[bBwW]
m : make ^ and $ apply to each \n separated line.
s : make . match all characters, include \n.
"""
def usage(e):
print '%s: %s' % (sys.argv[0], e)
print '%s -smMi <files>' % sys.argv[0], USAGE
sys.exit(-1)

try:
args, files = getopt.getopt(sys.argv[1:], 's:m:M:i')
except getopt.error, e:
usage(e)

for arg, value in args:
flag = 0
if arg == '-m':
regexp, flags = re.split(splitre, value)[1:]
for c in flags:
flag |= getattr(re, string.upper(c))
regexps.append(lambda s, r=regexp, f=flag: (re.search(r, s, f) and s)\
or '')
if arg == '-M':
regexp, flags = re.split(splitre, value)[1:]
for c in flags:
flag != getattr(re, string.upper(c))
regexps.append(lambda s, r=regexp, f=flag: ((not re.search(r, s, f))\
and s) or '')
if arg == '-s':
search, replace, flags = re.split(splitre, value)[1:]
for c in flags:
flag |= getattr(re, string.upper(c))
regexps.append(lambda s, se=search, r=replace, f=flag: re.sub(se, r,
s, f))
if arg == '-i':
inplace = 1

for line in fileinput.input(files, inplace):
for regexp in regexps:
line = regexp(line)
if line:
print line,


It's public domain, in case you like it.

Jeremy

kmj
03-28-2001, 11:44 AM
mind if I put this on the CCAE?

jemfinch
03-28-2001, 03:17 PM
No, that's fine. It just uses some higher-level things (and won't work until 2.1.)

Given that python's module documentation is so good, it makes little sense to document simple use of modules.

If I were you, I'd wait until 2.1 was officially released (about two weeks from now, I think.)

If there are any newbie pythoners here, they should read the code and post what they don't understand, so I can comment those sections. It's a bit hard for me to try and figure out which parts are tough leaps of programming and which are just normal (I'm a bit jaded.)

Jeremy