Skip to content

Instantly share code, notes, and snippets.

@simonLeary42
Created October 17, 2023 02:16
Show Gist options
  • Save simonLeary42/e2573ee190b8ee593164bf017a125a5b to your computer and use it in GitHub Desktop.
Save simonLeary42/e2573ee190b8ee593164bf017a125a5b to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import os
import sys
import glob
import zipfile
import tempfile
from subprocess import check_output, CalledProcessError
assert len(sys.argv) >= 3
grep_args = ' '.join(sys.argv[1:-1])
tmpdir = tempfile.TemporaryDirectory()
tmpdir_path = tmpdir.name
files_to_extract = glob.glob(sys.argv[-1])
if len(files_to_extract) == 0:
print(f"\"{sys.argv[-1]}\": no such file(s)")
sys.exit(1)
print("extracting...", end='\r')
for filename in files_to_extract:
this_tmpdir_path = os.path.join(tmpdir_path, f"{filename}.d")
os.mkdir(this_tmpdir_path)
with zipfile.ZipFile(filename, 'r') as file:
file.extractall(this_tmpdir_path)
try:
output = check_output(f"grep --color=always -r {grep_args} *", cwd=tmpdir_path, shell=True)
output_lines = output.decode().strip().splitlines()
for line in output_lines:
print(line)
except CalledProcessError as e:
print(f"{e.cmd} returned code {e.returncode}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment