Search text

2 snippets across 2 stacks - Bash & Linux, Python

SHBash & Linux

Search Text with Patterns

SH · Text Processing
Syntax
grep [options] pattern [file...]
Example
grep -rn 'TODO' src/
grep -i 'error' /var/log/syslog
grep -c 'SELECT' queries.sql
grep -v '^#' nginx.conf
Output
src/api/handler.go:42:  // TODO: add rate limiting
src/lib/cache.ts:18:  // TODO: implement TTL

Note -r searches recursively through directories. -n shows line numbers. -i is case-insensitive. -v inverts the match (shows non-matching lines). -c counts matches. -l lists only filenames with matches. Use -E for extended regex or egrep.

PYPython

re (Regular Expressions)

PY · Common Standard Library
Syntax
import re
re.search(pattern, string)
re.findall(pattern, string)
Example
import re

text = "Contact: [email protected] or [email protected]"
emails = re.findall(r"[\w.]+@[\w.]+\.\w+", text)
print(emails)

# Named groups
log = "2026-04-04 ERROR: Connection timeout"
match = re.match(r"(?P<date>[\d-]+) (?P<level>\w+): (?P<msg>.+)", log)
if match:
    print(match.group("level"), match.group("msg"))
Output
['[email protected]', '[email protected]']
ERROR Connection timeout

Note Always use raw strings (r'...') for regex patterns. For repeated use, compile with re.compile() for performance. Use re.VERBOSE for readable multi-line patterns.

Frequently asked questions

How do you search text?
This task is covered in 2 stacks on this page: Bash & Linux, Python. The "Search Text with Patterns" snippet in Bash & Linux uses `grep [options] pattern [file...]`.
Which command does the Bash & Linux example use?
The "Search Text with Patterns" snippet uses `grep [options] pattern [file...]`, from the Text Processing section of the Bash & Linux cheat sheet.
Which stacks cover "search text" on this page?
Bash & Linux, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Search Text with Patterns": -r searches recursively through directories. -n shows line numbers. -i is case-insensitive. -v inverts the match (shows non-matching lines). -c counts matches. -l lists only filenames with matches. Use -E for extended regex or egrep.