How can I use grep in Python

0 votes

There is a file (query.txt) which has some keywords/phrases which are to be matched with other files using grep. The last three lines of the following code are working perfectly but when the same command is used inside the while loop it goes into an infinite loop or something(ie doesn't respond).

import os

f=open('query.txt','r')
b=f.readline()
while b:
    cmd='grep %s my2.txt'%b    #my2 is the file in which we are looking for b
    os.system(cmd)
    b=f.readline()
f.close()

a='He is'
cmd='grep %s my2.txt'%a
os.system(cmd)
Dec 13, 2018 in Python by aryya
• 7,450 points
70,509 views

5 answers to this question.

0 votes

First of all, you are not iterating over the file properly. You can simply use for b in f: without the .readline() stuff.

Then your code will blow in your face as soon as the filename contains any characters which have a special meaning in the shell. Use subprocess.call instead of os.system() and pass an argument list.

Here's a fixed version:

import os
import subprocess
with open('query.txt', 'r') as f:
    for line in f:
        line = line.rstrip() # remove trailing whitespace such as '\n'
        subprocess.call(['/bin/grep', line, 'my2.txt'])

However, you can improve your code even more by not calling grep at all. Read my2.txt to a string instead and then use the re module to perform the search. In case you do not need a regex at all, you can even simply use if line in my2_content

Hope it works!!

If you are a beginner and need to know more about Python, It's recommended to go for Python Certification course today.

Thanks!

answered Dec 13, 2018 by charlie_brown
• 7,720 points
0 votes

Hi,

According to your description, you have to understand what is the use of grep command? How does grep command works? 

The grep command is used to search text or search the given file for lines containing a match to the given strings or words. By default, grep displays the matching lines. Use grep to search for lines of text that match one or many regular expressions, and outputs only the matching lines.

answered Jul 1, 2020 by Gitika
• 65,910 points
0 votes

Hello, 

Here goes a short demonstration on How do I use grep search? Because I found our concerned root are quite similar so, this is a way usage of the grep command which is demonstrated by the following example.

 Use the -r "recursive" option to search a directory and all files included within it. search the "hello" string in all files and # subdirectories of the current directory grep -r "hello"

answered Jul 1, 2020 by Nagaraj

edited Jul 2, 2020
An excellent post, congratulations !!
0 votes

Searching a file using grep will globally search for a regular expression and print the line.

answered Dec 14, 2020 by Roshni
• 10,520 points
0 votes

The first part starts with grep , followed by the pattern that you are searching for. After the string comes the file name that the grep searches through. The command can contain many options, pattern variations, and file names. Combine as many options as necessary to get the results you need.

answered Dec 14, 2020 by Gitika
• 65,910 points

Related Questions In Python

0 votes
1 answer

How can I use indices in math using python

Operator ^ is a bitwise operator, which does "bitwise exclusive or". More: http://wiki.python.org/moin/BitwiseOperators The ...READ MORE

answered Dec 11, 2018 in Python by aryya
• 7,450 points
1,694 views
0 votes
1 answer

How can I make use of getopt or optarg in Python?

Hi, I was asked this by one ...READ MORE

answered Feb 8, 2019 in Python by Nymeria
• 3,560 points
885 views
0 votes
0 answers

where and how can i use PYTHONPATH in python?

is there a particular syntax for this?? READ MORE

Apr 8, 2019 in Python by Waseem
• 4,540 points
465 views
0 votes
1 answer

How can I use the power function in python 2.7?

print(pow(3,4)) #this will return the exponentiation of 3 ...READ MORE

answered May 21, 2019 in Python by Mohammad
• 3,230 points
1,117 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,023 views
0 votes
1 answer
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,790 points
3,413 views
+2 votes
3 answers

How can I play an audio file in the background using Python?

down voteacceptedFor windows: you could use  winsound.SND_ASYNC to play them ...READ MORE

answered Apr 4, 2018 in Python by charlie_brown
• 7,720 points
12,874 views
0 votes
1 answer

How can I compare the content of two files in Python?

Assuming that your file unique.txt just contains ...READ MORE

answered Apr 16, 2018 in Python by charlie_brown
• 7,720 points
2,352 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP