Zohair
Zohair

Reputation: 505

What is the grep equivalent in Python?

Say I have a text file with the line 'I like elephants'. If I cat the said file and the pipe it to 'grep elephants', I get the entire line "I like elephants".

How do I achieve this functionality in Python with re? Ive been trying the following:

test = re.search('elephants', 'I like elephants.\nThey are nice')
test.group(0)

I get only the word 'elephants' and not the whole sentence as the output.

How do I get the entire sentence? Thank you.

Upvotes: 29

Views: 72326

Answers (1)

You could use the in keyword to check for your substring:

with open('text_file.txt', 'r') as f:
    for line in f.readlines():
        if 'elephant' in line:
            print(line)

Or, if you had a string s with \n characters:

for line in s.split('\n'):
    if 'elephant' in line:
        print(line)

Your regex only prints elephant because that's what it captured: exactly your regex string. If you were to try the following regex instead:

test = re.search(r'(.*?elephants.*?)\n', 'I like elephants.\nThey are nice')

Then you'd have results for test.group(0) and test.group(1) which include the whole line before and after the elephants.

In [22]: test.group(0)
Out[22]: 'I like elephants.\n'

That's the whole captured string.

In [23]: test.group(1)
Out[23]: 'I like elephants.'

That's just the capture group (string between parentheses).

Upvotes: 31

Related Questions