The grep command is one of the most powerful tools in Linux for searching text. It scans files or output and returns lines that match a pattern—perfect for logs, configs, and code.
🔎 What is grep?
grep stands for Global Regular Expression Print.
It lets you search for words, phrases, or patterns inside files.
✅ Basic Syntax
grep [options] "pattern" filename
📄 Example: Search a File
grep "error" logfile.txt
👉 Shows all lines in logfile.txt that contain the word error.
📁 Search Multiple Files
grep "error" *.txt
👉 Searches all .txt files in the current directory.
📂 Recursive Search (Folders)
grep -r "error" /var/log
👉 Searches inside all files in /var/log.
🔠 Case-Insensitive Search
grep -i "error" logfile.txt
👉 Matches error, Error, ERROR, etc.
🔢 Show Line Numbers
grep -n "error" logfile.txt
👉 Displays matching lines with line numbers.
❌ Invert Match (Exclude Results)
grep -v "error" logfile.txt
👉 Shows lines that do NOT contain “error”.
🎯 Exact Word Match
grep -w "error" logfile.txt
👉 Matches the exact word (not “errors” or “error123”).
🔥 Advanced: Use Regular Expressions
grep "^error" logfile.txt
👉 Lines that start with “error”
grep "error$" logfile.txt
👉 Lines that end with “error”
🔗 Combine with Other Commands
cat logfile.txt | grep "error"
👉 Filters output from another command
Better way:
grep "error" logfile.txt
📊 Count Matches
grep -c "error" logfile.txt
👉 Shows how many lines contain “error”
🚀 Pro Tips
- Use
grep -rfor full directory searches - Combine with
|(pipe) for powerful filtering - Use quotes around patterns to avoid shell issues
- Use regex for complex searches
👍 Summary
grepsearches text quickly- Works with files, folders, and command output
- Supports powerful pattern matching with regex
- Essential tool for developers and sysadmins
🎯 Final Thoughts
Mastering grep will save you hours when working in Linux. Start with simple searches, then move into recursive searches and regex for advanced tasks.