Linux Finding Text in Files
Finding Text in Files
grep
(General Regular Expression Print)
grep [options] pattern files
grep
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 *.txt
Searches all text files in the current directory for lines containing “hello”.
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 *.txt
Finds lines that do not contain any case variation of “hello”.
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
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.txt
Matches any 3-character line ending with letters l
to z
.
You can find a more detailed explanation on regex here: Regular Expressions
Variants
egrep
→ supports extended regex (|
,()
,+
,{}
ranges, etc.)fgrep
→ searches for fixed strings (likegrep -F
), faster for literal matches
Example with egrep
:
egrep '(^[0-9]{1,5}[a-zA-Z]+$)|none' file.txt
Matches lines that either:
- Start with up to 5 digits, followed by letters/spaces
- Or contain the word “none”
📌 More info: man grep
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
-
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