Skip to content

Linux Finding Text in Files

Finding Text in Files

grep (General Regular Expression Print)

Terminal window
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:

Terminal window
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):

Terminal window
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:

Terminal window
grep hello `find . -name "*.txt" -print`

Or use the recursive option:

Terminal window
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:

Terminal window
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 (like grep -F), faster for literal matches

Example with egrep:

Terminal window
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

CommandPurposeExample
grepSearch inside files for text patternsgrep -i "error" *.log
egrepExtended regex searchegrep “foo &#124 bar” file.txt
fgrepFixed string searchfgrep "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