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

Initial Version

grepy/grep.py:

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.

grepy_cli.py:

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:
        print(line)

if __name__ == '__main__':
    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:
PrevNext