PDA

View Full Version : [SOLVED] Python: search file like grep


dbbolton
June 6th, 2008, 04:59 AM
I want to do something like grep with python. I have a file, and I want to search it for a string, and print the line containing that string. Is this possible, and if so, how can I do it?

ghostdog74
June 6th, 2008, 05:45 AM
I want to do something like grep with python. I have a file, and I want to search it for a string, and print the line containing that string. Is this possible, and if so, how can I do it?


for line in open("file"):
if "search_string" in line:
print line

always read up the documentation and tutorials if you don't know anything.

dbbolton
June 6th, 2008, 06:20 AM
for line in open("file"):
if "search_string" in line:
print line

always read up the documentation and tutorials if you don't know anything.
Thanks. I have been reading the docs and a few tutorials, but I got stuck on this one.

Also, do you know whether it's possible to print only the first occurrence of the search string?

WW
June 6th, 2008, 06:29 AM
Also, do you know whether it's possible to print only the first occurrence of the search string?
Just put a break statement after the print statement.

dbbolton
June 6th, 2008, 06:44 AM
Thanks :)

helpdeskdan
November 5th, 2008, 02:59 PM
Another thanks!

jdb91
October 7th, 2010, 06:30 AM
So I'm doing

for line in open("text.txt"):
if "ref" in line:
print line


And getting back

ref= 1

(For example)

All I want displayed is the "1"

How do I format the output of print line to print just the second part (in bash it would be awk {print $2})

ghostdog74
October 8th, 2010, 10:06 PM
you just need to split .

print line.split("=")[-1]


i thought you have been reading the docs? split() is very basic for Python string processing.