typestar

grep_lite.py in Python

A minimal grep: find lines matching a pattern across files.

"""A minimal grep: search files for a pattern, print matching lines."""
import sys
from pathlib import Path


def search_file(path, needle):
    matches = []
    try:
        text = path.read_text(errors="ignore")
    except OSError:
        return matches
    for number, line in enumerate(text.splitlines(), start=1):
        if needle in line:
            matches.append((number, line.strip()))
    return matches


def main():
    if len(sys.argv) < 3:
        print("usage: grep_lite.py PATTERN PATH [PATH...]")
        raise SystemExit(1)
    needle = sys.argv[1]
    total = 0
    for arg in sys.argv[2:]:
        root = Path(arg)
        files = root.rglob("*") if root.is_dir() else [root]
        for path in files:
            if not path.is_file():
                continue
            for number, line in search_file(path, needle):
                print(f"{path}:{number}: {line}")
                total += 1
    print(f"{total} matching lines")


if __name__ == "__main__":
    main()

How it works

  1. Reads the pattern and paths from sys.argv.
  2. rglob walks directories; files are scanned line by line.
  3. Prints path:line: matches and a final count.

Keywords and builtins used here

The run, in numbers

Lines
37
Characters to type
806
Tokens
218
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 125 seconds.

Type this snippet

Step 4 of 5 in Encore, step 71 of 72 in Language basics.

← Previous Next →