03. Filtering Stuffs Using grep
Overview¶
The grep command is used to search for specific patterns or strings within files or command outputs. It is one of the most powerful tools in Linux for:
-
Log analysis
-
Data filtering
-
Bug hunting and reconnaissance
-
Text processing
Basic Syntax¶
Explanation
-
grep→ command used for searching -
"pattern"→ string or regex to search -
filename→ file to search in
Basic Example¶
Explanation
Displays all lines in file.txt that contain the word dynamic.
Case Sensitivity¶
By default, grep is case-sensitive.
Example¶
-
Matches
hello -
Does NOT match
HelloorHELLO
Ignore Case (-i)¶
Explanation
-
Matches
hello,Hello,HELLO, etc. -
Useful when case is unknown
Search in Multiple Files¶
Explanation
Searches for "error" in multiple files.
Recursive Search (-r)¶
Explanation
-
Searches inside all files and subdirectories
-
Useful for finding sensitive data or keywords
Show Line Numbers (-n)¶
Explanation
Displays matching lines along with their line numbers.
Count Matches (-c)¶
Explanation
Returns the number of matching lines.
Invert Match (-v)¶
Explanation
Shows lines that do not contain the pattern.
Exact Word Match (-w)¶
Explanation
Matches only the exact word admin, not partial matches like administrator.
Using grep with Pipe (|)¶
Concept of Piping¶
Piping (|) allows output of one command to be used as input for another.
Example with cat¶
Explanation
-
cat file.txt→ outputs file content -
grep "root"→ filters lines containing "root"
Better Alternative¶
Note
Direct use of grep is more efficient than piping with cat.
Using grep with locate¶
Example¶
Explanation
-
locate filename→ finds all matching files -
grep "/path"→ filters results based on path
Using grep with Other Commands¶
Example with ps¶
Explanation
-
Lists running processes
-
Filters processes related to
apache
Example with netstat¶
Explanation
-
Shows network ports
-
Filters results for port 80
Regular Expressions (Basic Usage)¶
Explanation
-
^→ matches start of line -
Finds lines starting with
root
Explanation
-
$→ matches end of line -
Finds lines ending with
error
Important Notes¶
-
Always enclose patterns in quotes
" " -
Use
-iwhen case is uncertain -
Use
-rfor directory-wide searches -
Combine with other commands for powerful filtering
Summary Table¶
| Option | Description |
|---|---|
-i |
Ignore case |
-r |
Recursive search |
-n |
Show line numbers |
-c |
Count matches |
-v |
Invert match |
-w |
Exact word match |
Conclusion¶
The grep command is a core tool in Linux widely used in:
-
Log analysis
-
Penetration testing
-
Automation scripts
-
System monitoring
Mastering grep significantly improves your ability to analyze and filter data efficiently in any Linux environment.