Linux Finding Text in Files
Finding Text in Files
Section titled “Finding Text in Files”grep (General Regular Expression Print)
Section titled “grep (General Regular Expression Print)”grep [options] pattern filesgrep searches the specified files (or standard input if none are given) for lines matching a pattern.
By default, it prints matching lines.
Example:
grep hello *.txtSearches all text files in the current directory for lines containing “hello”.
Useful Options
Section titled “Useful Options”- -c→ print the count of matching lines
- -i→ ignore case
- -v→ invert match (show lines that don’t match)
- -n→ show line numbers
Example (ignore case + invert match):
grep -vi hello *.txtFinds lines that do not contain any case variation of “hello”.
Searching Recursively
Section titled “Searching Recursively”Combine with find to search across a directory tree:
grep hello `find . -name "*.txt" -print`Or use the recursive option:
grep -r hello .Regular Expressions
Section titled “Regular Expressions”grep uses regular expressions for powerful pattern matching.
- ^→ start of line
- $→ end of line
- .→ any character
- [0-9]→ any digit
- [^a-z]→ any non-lowercase letter
Example:
grep ^..[l-z]$ hello.txtMatches any 3-character line ending with letters l to z.
You can find a more detailed explanation on regex here: Regular Expressions
Variants
Section titled “Variants”- egrep→ supports extended regex (- |,- (),- +,- {}ranges, etc.)
- fgrep→ searches for fixed strings (like- grep -F), faster for literal matches
Example with egrep:
egrep '(^[0-9]{1,5}[a-zA-Z]+$)|none' file.txtMatches lines that either:
- Start with up to 5 digits, followed by letters/spaces
- Or contain the word “none”
📌 More info: man grep
Comparison
Section titled “Comparison”| Command | Purpose | Example | 
|---|---|---|
| grep | Search inside files for text patterns | grep -i "error" *.log | 
| egrep | Extended regex search | egrep “foo | bar” file.txt | 
| fgrep | Fixed string search | fgrep "hello world" file.txt | 
Other Useful Tips
Section titled “Other Useful Tips”- 
Search text in compressed files: 
 zgrep pattern file.gz
- 
Count matches across many files: 
 grep -r -c "error" /var/log
- 
Get top 10 most frequent words in a file: Terminal window tr -cs '[:alnum:]' '[\n*]' < file.txt | sort | uniq -c | sort -nr | head -10