[Tutor] Grep equiv.

Wes Bateman wbateman@epicrealm.com
Thu, 31 Aug 2000 11:23:10 -0500 (CDT)


Still not able to get exactly what I want.  Really a result exactly like
grep does is what I'm looking for.  I want to examine a file, line by
line, and return the lines that contain a string that I was searching
for.  To do this using string.find, I tried the following.  This searches
for the string 'sdb' in a file, and I only want it to kick back the lines
that contain the string.

I think that it's looking at the whole file, if it contains the string, it
spits the whole file back, if it doesn't contain the string, it returns
nothing.  How can I break up the piece that I'm feeding the string.find
into lines, so that I can tell it what to do line by line?

I tried to use string.splitfields(line) to break it up, but it used a
whitespace delimeter and divided each line up.  If I did this the
string.find choked on the list variable type.  Which raises other
questions I have about how I can perform a particular function on all of
the items in a list ( variable[0], variable[1], variable[2], etc.) in one
pass?

Further, what would be the preferred way to suck a file in, put each line
in a variable, and each field in each line inside of that?  I understand
that I can nest lists, so maybe like file[0] is first line of file and
inside of that there could be several fields?  How would I reference them
and how could I get them into a structure like that?

Eventually I want to take say the third field from each line that matches
my "grep-like" function and add them.

Thanks :)

Wes

	#!/usr/bin/python
	
	import sys
	import string
	import re
	
	filename = sys.argv[1]
	
	file = open(filename)
	for line in file.readlines():
		result = string.find(line,'sdb')
		if result != '-1' :
			print line
	file.close()