finding a regular expression in a file

S

S.B

Hello friends.

Newb question here.
I'm trying to find an efficient way to "grep" a file with python.
The problem is that all the solutions I find on the web read a line at a time from the file with a "for line in" loop and check each line for the RE instead of sweeping through the entire file.
This looks terribly inefficient...

I can read the entire file like so:
open("/etc/passwd").read()
and use that in an re.search - e.g:
re.search("root",open("/etc/passwd").read())
The above will work BUT it will not interpolate the "\n" as a newline and will just print the entire file as a long line.
So if I try to look for '^root' (line starting with root) instead of 'root' it will NOT work

any ideas on how to get around this?

Thanks.
 
J

Jussi Piitulainen

S.B said:
Hello friends.

Newb question here.
I'm trying to find an efficient way to "grep" a file with python.
The problem is that all the solutions I find on the web read a line
at a time from the file with a "for line in" loop and check each
line for the RE instead of sweeping through the entire file.
This looks terribly inefficient...

I can read the entire file like so:
open("/etc/passwd").read()
and use that in an re.search - e.g:
re.search("root",open("/etc/passwd").read())
The above will work BUT it will not interpolate the "\n" as a
newline and will just print the entire file as a long line.
So if I try to look for '^root' (line starting with root) instead of
'root' it will NOT work

any ideas on how to get around this?

Check MULTILINE mode in the documentation: ^ "Matches the start of the
string, and in MULTILINE mode also matches immediately after each
newline."
 
S

S.B

Check MULTILINE mode in the documentation: ^ "Matches the start of the
string, and in MULTILINE mode also matches immediately after each
newline."

PERFECT!!! - Thanks :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top