[Tutor] newbie question about grep in Python
Rich Krauter
rmkrauter at yahoo.com
Tue Feb 10 18:52:14 EST 2004
On Tue, 2004-02-10 at 17:26, Eric Culpepper wrote:
> I'm trying my best to learn Python and I'm going through some shell
> scripts attempting to write Python versions of these scripts. I
> stumbled on this piece of a script and I'm struggling to figure out a
> method of doing this in Python.
>
> #!/bin/sh
> o_date=`strings /shc1/$1/$2 2> /dev/null | grep Date | egrep
> "\#V\#|\@\(\#\)" \
> | sed 's/^\\$//' | awk 'BEGIN {FS="$"}
> {printf("%s\n",substr($2,6))}'`
> echo "o_date is $o_date"
>
Here's a first attempt. Others will have better ideas:
import re
import struct
import sys
if __name__ == '__main__':
pat = re.compile(r'#V#\$Date:(.+?)\$#V#')
for f in sys.argv[1:]:
mystr = ''
fobj = open(f,'r')
while 1:
buf = fobj.read(1024)
if not buf: break
fmt = '%ss'%len(buf)
mystr += str(struct.unpack(fmt,buf))
fobj.close()
mobj = re.search(pat,mystr)
if mobj is not None:
print 'Found %s in %s'%(mobj.group(1),f)
In words:
I construct my pattern (which may be too restrictive). I then loop over
the input files, opening each. While I can read bytes into a buffer, I
see how long the buffer is and use that length as my format string
argument to sruct.unpack, along with the 's' format specifier. I build
up mystr, using concatenation, from the unpacked chucks of the file I
read in. Once I have my complete string, I close the file and try to
create a match object. If the match succeeds, I print out what I find.
Probably not the best way to do it, but perhaps it's a starting point.
I'd appreciate suggestions for improvement.
Thanks.
Rich
More information about the Tutor
mailing list