» Make grep CLI App in Python » 2. Development » 2.2 Initial Version

Initial Version


import re

def grep(pattern, file_path):
    with open(file_path, 'r') as file:
        lines = file.readlines()
        matching_lines = [line.strip() for line in lines if re.search(pattern, line)]
        return matching_lines

The re module provides support for regular expressions, which are powerful tools for pattern matching and text manipulation.


import argparse

from grepy.grep import grep

def main():
    parser = argparse.ArgumentParser(description='A grep-like command-line utility from LiteRank')
    parser.add_argument('pattern', type=str, help='The pattern to search for')
    parser.add_argument('file_path', type=str, help='The path to the file to search in')
    args = parser.parse_args()

    result = grep(args.pattern, args.file_path)
    for line in result:

if __name__ == '__main__':

The argparse module is used for parsing command-line arguments and options in a user-friendly manner. It allows you to define the arguments your script should accept and automatically generates help messages.

Run the CLI script like this:

# search "result" in file grepy_cli.py
python3 -m grepy_cli result grepy_cli.py

You will get result lines like below:

result = grep(args.pattern, args.file_path)
for line in result: