How to use Grep Command
The grep command is one of the most useful tools in Linux/Unix for searching text. It scans files or streams line by line and prints the lines that match a given pattern.
🔑 Basic Syntax
grep [options] pattern [file...]
- pattern → the text or regex you want to search for
- file → the file(s) you want to search in
📘 Common Examples
Search for a word in a file
grep "error" logfile.txt→ Shows all lines in
logfile.txtcontaining the word error.Case-insensitive search
grep -i "error" logfile.txt→ Matches Error, ERROR, error, etc.
Search recursively in a directory
grep -r "TODO" ./src→ Finds all lines with TODO in files under
./src.Show line numbers
grep -n "main" program.c→ Displays matching lines with their line numbers.
Count matches
grep -c "error" logfile.txt→ Prints how many lines contain error.
Use regex patterns
grep "^[0-9]" data.txt→ Matches lines starting with a digit.
⚡ Useful Options
| Option | Meaning |
|---|---|
-i | Ignore case |
-n | Show line numbers |
-r | Recursive search in directories |
-v | Invert match (show lines not matching) |
-c | Count matches |
-E | Use extended regex (like egrep) |
Comments
Post a Comment