Skip to content

Instantly share code, notes, and snippets.

@raresteak
Created August 28, 2023 01:12
Show Gist options
  • Save raresteak/3f32430573c42474385540ac95d36dea to your computer and use it in GitHub Desktop.
Save raresteak/3f32430573c42474385540ac95d36dea to your computer and use it in GitHub Desktop.
Mimic nix grep with Python3
import re
import argparse
parser = argparse.ArgumentParser(description='Mimic Linux grep command for Python')
parser.add_argument('pattern', type=str, help='The pattern to search for')
parser.add_argument('file', type=str, help='The file to search in')
parser.add_argument('-i', '--ignore-case', action='store_true', help='Perform case-insensitive search')
args = parser.parse_args()
if args.ignore_case:
pattern = re.compile(args.pattern, re.IGNORECASE)
else:
pattern = re.compile(args.pattern)
with open(args.file) as f:
for line in f:
if pattern.search(line):
print(line.rstrip())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment