Pesquisa e Regex
Encontre arquivos por nome, pesquise texto dentro de arquivos e use padrões regex - a habilidade principal para navegar em qualquer base de código a partir do terminal.
Busque em todas as páginas da documentação
Encontre arquivos por nome, pesquise texto dentro de arquivos e use padrões regex - a habilidade principal para navegar em qualquer base de código a partir do terminal.
🤖 Read the SystemsArchitect.io Blog for over 100+ cloud architecture articles 🔥
Cartão de receita de referência rápida - pronto para copiar e colar.
# Find files by name
find . -name "*.tsx" -type f
find . -name "page.tsx" -path "*/app/*"
# Search text inside files
grep -r "useState" src/
grep -rn "TODO" --include="*.ts" .
# Faster alternative (ripgrep)
rg "useState" src/
rg "TODO" -t ts
# Find and replace across files
sed -i '' 's/oldFunction/newFunction/g' src/**/*.tsQuando usar isso: Quando você precisar encontrar um arquivo, localizar onde uma função está sendo usada, pesquisar um padrão em toda a base de código ou fazer uma substituição em massa de encontrar e substituir.
# "Where is this component defined?"
rg "export.*function Header" --include="*.tsx"
# or
grep -rn "export.*function Header" --include="*.tsx" src/
# "Which files import this module?"
rg "from.*@/components/Button" -l
# -l = files only, no matching lines
# "Find all TODO comments with context"
rg "TODO|FIXME|HACK" -t ts -t tsx -C 2
# -C 2 = show 2 lines of context above and below
# "Find large files in the project"
find . -type f -size +1M -not -path "./node_modules/*" -not -path "./.next/*"O que isso demonstra:
grep -rn para pesquisa recursiva com números de linharg (ripgrep) é significativamente mais rápido e ignora automaticamente os padrões .gitignore-l mostra apenas nomes de arquivos, útil para canalizar para outros comandosfind combinado com -not -path para excluir diretórios# Basic name search (case-sensitive)
find . -name "layout.tsx"
# Case-insensitive
find . -iname "readme*"
# By file type
find . -type f # files only
find . -type d # directories only
# By extension pattern
find . -name "*.test.ts"
find . -name "*.md" -o -name "*.mdx" # OR
# Exclude directories
find . -name "*.ts" -not -path "*/node_modules/*" -not -path "*/.next/*"
# By modification time
find . -name "*.tsx" -mtime -1 # modified in last 24 hours
find . -name "*.tsx" -mmin -60 # modified in last 60 minutes
find . -name "*.tsx" -newer reference.txt # newer than a file
# By size
find . -type f -size +500k # larger than 500KB
find . -type f -size -1k # smaller than 1KB
find . -type f -empty # empty files
# Execute a command on results
find . -name "*.test.ts" -exec wc -l {} \;
find . -name "*.log" -exec rm {} \;
find . -name "*.tsx" -exec grep -l "useState" {} \;
# Using xargs (often faster for many files)
find . -name "*.ts" | xargs grep "deprecated"
find . -name "*.tmp" -print0 | xargs -0 rm # handle spaces in filenames# Basic recursive search
grep -r "pattern" directory/
# With line numbers
grep -rn "useState" src/
# Case insensitive
grep -rni "error" src/
# Only filenames (no matching lines)
grep -rl "useEffect" src/components/
# Invert match (lines NOT matching)
grep -v "node_modules" file.txt
# Count matches per file
grep -rc "import" src/ | sort -t: -k2 -rn | head -10
# Filter by file extension
grep -rn "fetchData" --include="*.ts" --include="*.tsx" .
grep -rn "TODO" --include="*.{ts,tsx}" .
# Exclude directories
grep -rn "console.log" --exclude-dir=node_modules --exclude-dir=.next .
# Show context around matches
grep -rn "error" -A 3 src/ # 3 lines After
grep -rn "error" -B 2 src/ # 2 lines Before
grep -rn "error" -C 2 src/ # 2 lines Context (both)
# Match whole words only
grep -rw "use" src/ # matches "use" but not "useState"
# Multiple patterns
grep -rn -e "useState" -e "useEffect" src/# Install
# macOS: brew install ripgrep
# Ubuntu: sudo apt install ripgrep
# Basic search (auto-ignores .gitignore patterns)
rg "pattern" src/
# Filter by file type
rg "useState" -t tsx
rg "TODO" -t ts -t tsx
# Only filenames
rg "useEffect" -l
# Files NOT matching
rg "useEffect" --files-without-match -t tsx
# Fixed string (no regex interpretation)
rg -F "array.map((item) =>" src/
# Multiline search
rg -U "export default function.*\n.*return" src/
# Replace (preview - does not modify files)
rg "oldName" -r "newName"
# Show stats
rg "TODO" --stats
# Search hidden files too
rg "SECRET" --hidden
# Glob patterns
rg "fetch" -g "*.ts" -g "!*.test.ts" # ts files but not test files# Anchors
^start # line starts with "start"
end$ # line ends with "end"
^exact$ # entire line is "exact"
# Character classes
[abc] # a, b, or c
[a-z] # lowercase letter
[0-9] # digit
[^abc] # NOT a, b, or c
. # any single character
# Quantifiers
a* # zero or more a's
a+ # one or more a's
a? # zero or one a
a{3} # exactly 3 a's
a{2,5} # 2 to 5 a's
# Groups and alternation
(foo|bar) # foo or bar
(abc)+ # one or more "abc" sequences
# Common shortcuts
\d # digit [0-9] (extended regex)
\w # word char [a-zA-Z0-9_]
\s # whitespace
\b # word boundary
# Escape special characters
\. # literal dot
\( # literal parenthesis# Find React component definitions
rg "export (default )?(function|const) [A-Z]\w+"
# Find all hook calls
rg "use[A-Z]\w+\(" -t tsx
# Find console.log statements (but not console.error/warn)
rg "console\.log\(" src/
# Find TODO with author
rg "TODO\([^)]+\):" src/
# Find hardcoded URLs
rg "https?://[^\s\"')\]>]+" src/
# Find empty catch blocks
rg -U "catch\s*\([^)]*\)\s*\{\s*\}" src/
# Find imports from a specific package
rg "from ['\"]react['\"]" src/
# Find CSS color hex codes
rg "#[0-9a-fA-F]{3,8}\b" src/
# Find potential API keys (basic pattern)
rg "['\"][A-Za-z0-9_]{20,}['\"]" --include="*.ts" src/
# Find duplicate adjacent words (typos)
rg "\b(\w+)\s+\1\b" docs/# Replace in a single file (macOS - '' is required)
sed -i '' 's/oldText/newText/g' file.tsx
# Replace in a single file (Linux)
sed -i 's/oldText/newText/g' file.tsx
# Preview without modifying (works on both)
sed 's/oldText/newText/g' file.tsx
# Replace across multiple files
find src -name "*.tsx" -exec sed -i '' 's/OldComponent/NewComponent/g' {} \;
# Replace with regex
sed -i '' 's/className="text-[a-z]*"/className="text-base"/g' file.tsx
# Delete lines matching a pattern
sed -i '' '/console\.log/d' src/app/page.tsx
# Replace only on lines matching a condition
sed -i '' '/import/s/react/react-dom/' file.tsx# Print specific columns
ps aux | awk '{print $1, $2, $11}' # user, PID, command
# Sum a column
wc -l src/**/*.tsx | awk '{sum += $1} END {print sum " total lines"}'
# Filter by condition
df -h | awk '$5 > "80%"' # disks over 80% full
# Print lines between patterns
awk '/START/,/END/' file.txt
# Count unique values
git log --format="%an" | sort | uniq -c | sort -rnCoisas que vão te morder. Cada armadilha inclui o que dá errado, por que acontece e a correção.
grep pesquisa node_modules - Sem --exclude-dir, grep pesquisa tudo e leva uma eternidade. Correção: Use rg (respeita .gitignore automaticamente) ou adicione --exclude-dir=node_modules.
find retorna muitos resultados - Pesquisando a partir de / ou sem excluir diretórios. Correção: Sempre escopo sua pesquisa: find src/ ... e use -not -path.
diferenças do sed entre macOS e Linux - O sed do macOS requer -i '' (string vazia para extensão de backup), o Linux não. Correção: Use sed -i '' 's/.../.../' file no macOS ou instale o GNU sed: brew install gnu-sed.
metacaracteres de regex em strings de pesquisa - Pesquisando [, ., ( literais etc. sem escapar. Correção: Use grep -F ou rg -F para strings fixas (não regex).
resultados ausentes com regex básico do grep - Alguns padrões como \d, +, \w precisam de regex estendido. Correção: Use grep -E (estendido) ou grep -P (compatível com Perl) para padrões avançados.
Outras maneiras de resolver o mesmo problema - e quando cada uma é a melhor escolha.
| Alternativa | Use Quando | Não Use Quando |
|---|---|---|
rg (ripgrep) | Pesquisa rápida de base de código, respeita .gitignore | Não instalado no servidor |
ag (silver searcher) | Semelhante ao rg, já instalado | rg está disponível (rg é geralmente mais rápido) |
fd | Substituto moderno para find com sintaxe mais simples | Scripting que precisa de compatibilidade com find POSIX |
| Pesquisa do IDE (Cmd+Shift+F) | Contexto visual, navegação rápida para resultados | Scripting, automação ou servidores remotos |
fzf | Encontrar arquivos e conteúdo de forma difusa e interativa | Correspondência exata de padrões necessária |
rg é significativamente mais rápido, especialmente em bases de código grandesrg ignora automaticamente arquivos listados em .gitignoregrep vem pré-instalado em todos os lugares; rg pode precisar ser instalado separadamentegrep -F "array.map((item) =>" src/
# or
rg -F "array.map((item) =>" src/-F trata o padrão como uma string fixa, não como uma regexfind . -name "*.tsx" -mmin -60-mmin -60 significa modificado há menos de 60 minutos-mtime -1 significa modificado nas últimas 24 horasgrep: grep -rn "pattern" --exclude-dir=node_modules .find: find . -name "*.ts" -not -path "*/node_modules/*"rg: automático (respeita .gitignore)-E habilita regex estendido (suporta +, ?, |, () sem escapar)-P habilita regex compatível com Perl (suporta \d, \w, \b, lookaheads)-E para a maioria dos casos; use -P quando precisar de padrões avançadossed do macOS requer uma string vazia para edição in-place: sed -i '' 's/old/new/g' filesed do Linux não: sed -i 's/old/new/g' filebrew install gnu-sed para um comportamento consistenterg "export (default )?(function|const) [A-Z]\w+" -t tsxfind src -name "*.tsx" -exec sed -i '' 's/OldName/NewName/g' {} \;sed 's/OldName/NewName/g' file.tsx (sem -i)grep básico não suporta \d; use [0-9] em vez dissogrep -P "\d+" file ou grep -E "[0-9]+" filegrep -rc "import" src/ | sort -t: -k2 -rn | head -10-c imprime uma contagem por arquivo em vez de linhas correspondentesrg -U "catch\s*\([^)]*\)\s*\{\s*\}" src/-U habilita correspondência multilinhasrg "^(export )?(type|interface) \w+" -t tstype e interface-l para listar apenas os caminhos dos arquivosRevisado por Chris St. John·Última atualização: 10 de jul. de 2026
🤖 Read the SystemsArchitect.io Blog for over 100+ cloud architecture articles 🔥