Python

How to Run Grep in Python

Have you ever considered looking for a string in a folder’s files? You’re probably familiar with the grep command if you’re a Linux user. You can create your command using Python programming to search for a string pattern in the specified files. The application also allows you to search for patterns utilizing regular expressions.

Using Python in Windows, you can simply search text strings from files in a specific folder. The grep command is available on Linux; however, it is not present on Windows. The only other option is to write a command to find the string.

This article will teach you how to use the grep tool and then use regular expressions to perform more advanced searches. There are also some Python grep examples to help you learn how to use it.

What is GREP?

One of the most beneficial commands is the grep command. GREP is a useful command-line tool that lets us use regular expressions to search plain text files for specified lines. In Python, regular expressions (RE) are commonly used to determine whether a string matches a specific pattern. Regular expressions are fully supported by Python’s re package. The re module throws the re.error exception when an error occurs while using regular expressions.

The GREP term means you can use grep to see if the data it gets matches a pattern you specify. This seemingly innocuous program is highly powerful; its ability to sort input according to sophisticated rules is a common component in many command chains.

The grep utilities are a group of file-searching programs that comprise grep, egrep, and fgrep. Because of its quickness and ability to merely look at strings and words, fgrep is sufficient for most use cases. On the other hand, Typing grep is simple and can be used by anyone.

Example 1:

When you use grep in Python to search a file, it will look for a regular expression globally and output the line if it finds one. For Python grep, follow the guidelines below.

The first step is to use the open() function in Python. As the name says, the open() function is used for the purpose of opening a file. Then, using the file, write the content inside the file, and for this, write() is a function that is used for writing text. After that, you can save the file with the name you like.

Now, create a pattern. Let’s say we wish to search a file for the term “coffee.” We need to examine that keyword, so we’ll use the open() function to open the file.

To compare a string alongside a regular expression, you can use the re.search() function. Using a regular expression pattern and a string, the re.search() method looks for a regular expression pattern within a string. Search() method will return a match object if the search is successful.

Import the re module at the top of the code to deal with regular expressions in R. We’ll print the entire line if it detects a match using a regular expression. For example, we are looking for the word “Coffee”, and if it is found, it will print it. The whole code can be found below.

import re

file_one = open("new_file.txt", "w")

file_one.write("Coffee\nPlease")

file_one.close()

patrn = "Coffee"

file_one = open("new_file.txt", "r")

for word in file_one:

    if re.search(patrn, word):

        print(word)

Here you can see that the word “Coffee” is printed in the output.

Example 2:

Call open(file location, mode) using the file location and mode as “r” to open a file for reading in the following code. We first imported the re module and then opened the file by giving the file name and mode.

We are using a for-loop, loop through the lines in the file. Use the if statement if re.search(pattern, line) to search for a regular expression or string, with the pattern being the regular expression or string to look for and the line being the current line in the file.

import re

file_one = open("demo.txt", "w")

file_one.write("first line of text\nsecond line of text\nthird line of text")

file_one.close()

patrn = "second"

file_one = open("demo.txt", "r")

for line in file_one:

    if re.search(patrn, line):

        print(line)

Here, the complete line is printed where the pattern is found.

Example 3:

Regular expressions can be handled with Python’s re package. We’ll try to execute GREP in Python and examine a file for a definite pattern in the code given below. We use the reading mode to open the appropriate file and loop through it line by line. Then we use the re.search() method to find the required pattern in each line. The line is printed if the pattern is detected.

import re

with open("demo.txt","r") as file_one:

    patrn = "second"

    for line in file_one:

        if re.search(patrn, line):

            print(line)

Here is the output, which clearly shows that the pattern is found in the file.

Example 4:

There’s another brilliant way to do this with Python via the command line. This method employs the command line to specify the regular expression and the file to be searched, and not forget the terminal to execute the file. This permits us to accurately reproduce GREP in Python. This is done with the code below.

import re

import sys

with open(sys.argv[2],"r") as file_one:

    for line in file_one:

        if re.search(sys.argv[1], line):

            print(line)

The sys module’s argv() function generates a sequence containing all of the arguments supplied to the command line. We can save it by the name of grep.py and run a specific Python script from the shell with the subsequent arguments.

Conclusion:

To search a file employing grep in Python, import the “re” package, upload the file, and use a for loop to iterate over each line. On each iteration, use the re.search() method and the RegEx expression as the primary argument and the data line as the second. We’ve gone over the topic in detail with several examples in this article.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content