Skip to content

Instantly share code, notes, and snippets.

@rupeshs
Last active August 11, 2025 02:57
Show Gist options
  • Select an option

  • Save rupeshs/6e86b37d1f6506a7df0b78dd61b6ebc5 to your computer and use it in GitHub Desktop.

Select an option

Save rupeshs/6e86b37d1f6506a7df0b78dd61b6ebc5 to your computer and use it in GitHub Desktop.
Search code with n number of lines above and below
import glob
import os
# === CONFIG ===
SEARCH_DIR = r"G:\2025\tests\fastsdcpu\src" # Change to your folder
SEARCH_TERM = "test" # Search string
CONTEXT_LINES = 0 # Lines above & below
CASE_SENSITIVE = True # Set False for case-insensitive
OUTPUT_FILE = "result.txt"
# ==============
def search_in_file(file_path):
results = []
try:
with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
lines = f.readlines()
for i, line in enumerate(lines):
if CASE_SENSITIVE:
match = SEARCH_TERM in line
else:
match = SEARCH_TERM.lower() in line.lower()
if match:
start = max(0, i - CONTEXT_LINES)
end = min(len(lines), i + CONTEXT_LINES + 1)
context = "".join(lines[start:end])
results.append((file_path, i + 1, context))
except Exception as e:
print(f"Error reading {file_path}: {e}")
return results
cpp_files = glob.glob(os.path.join(SEARCH_DIR, "**", "*.cpp"), recursive=True)
h_files = glob.glob(os.path.join(SEARCH_DIR, "**", "*.h"), recursive=True)
all_files = cpp_files + h_files
all_results = []
for file_path in all_files:
all_results.extend(search_in_file(file_path))
with open(OUTPUT_FILE, "w", encoding="utf-8") as out:
hit_count = 0
for file_path, line_num, context in all_results:
hit_count += 1
out.write(f"\n Hit {hit_count} ===== FILE: {file_path} (Line {line_num}) =====\n")
out.write(context)
out.write("\n")
print(f"Search complete. Results saved to {OUTPUT_FILE}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment