How to Search Text or String in Files on Linux

These examples demonstrate grep’s powerful text-searching capabilities, making it an essential tool for system administrators and developers.

Alby Andersen

The grep command in Linux is a powerful text-search utility that scans files or input streams for lines matching a specified pattern using regular expressions. Short for “Global Regular Expression Print,” grep is indispensable for filtering logs, analyzing code, and extracting specific data.

grep "error" logfile.txt


Searches for the word “error” in logfile.txt and prints matching lines.


grep -i "warning" logfile.txt
  • -i ignores case, matching “Warning”, “WARNING”, etc.

Recursive Search in Directories

grep -r "TODO" /path/to/project
  • -r searches recursively through all files in the directory.

Display Line Numbers

grep -n "404" access.log
  • -n shows line numbers for matches (e.g., 42:404 Not Found).

5. Highlight Matches

grep --color=auto "success" output.log


Highlights the matched text in color for easier visibility.


Count Matching Lines

grep -c "GET" access.log
  • -c returns the number of lines containing “GET”.

Invert Match (Exclude Lines)

grep -v "debug" app.log
  • -v prints lines not containing “debug”.

8. Search for Whole Words

grep -w "port" config.txt
  • -w matches “port” as a whole word (ignores substrings like “export”).

Pipe Input from Another Command

cat access.log | grep "POST"


Filters the output of cat to show lines with “POST”.


Use Regular Expressions (Email Pattern)

grep -E "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}" users.txt
  • -E enables extended regex to match email addresses.

Search Multiple Files with Wildcards

grep "panic" *.log


Searches for “panic” in all .log files in the current directory.


Combine with find for Advanced Searches

find /var/log -type f -name "*.log" -exec grep "failed" {} \;


Searches for “failed” in all .log files under /var/log.


Search Compressed Files

zgrep "error" /var/log/syslog.1.gz


Searches inside gzipped files without decompressing them.


Display Context Around Matches

grep -C3 "crash" app.log
  • -C3 shows 3 lines before and after the matching line.
  • Use -B (before) or -A (after) for one-directional context.

Extended Grep (egrep) for Multiple Patterns

egrep "error|warning|critical" system.log


Matches lines containing “error”, “warning”, or “critical”.

Search for a String in Command Output

ps aux | grep "firefox"

Filters processes to show only those related to firefox.


Key Notes:

  • Regular Expressions: Use grep -E or egrep for advanced patterns.
  • Performance: Avoid grep on huge files—use tools like less or awk instead.
  • Exclude Directories: Add --exclude-dir=.git to skip specific folders in recursive searches.
Share This Article