grep - Search for Text in Files

Learn grep to search files for patterns. Find errors in logs, locate config values, and filter output instantly.

commandsLast updated 2026-02-24

grep: Find the Needle in the Haystack

You have a 10,000 line log file. Somewhere in there is the word "error." Good luck scrolling.

Or:

grep "error" log.txt

Every line containing "error" appears. Everything else vanishes. That's grep.

The Basic Pattern

grep "pattern" file.txt

grep prints every line that contains your pattern. Simple as that.

The Flags You'll Actually Use

Case-insensitive:

grep -i "error" log.txt

Matches "error", "Error", "ERROR", whatever.

Show line numbers:

grep -n "error" log.txt

Now you know it's on line 847.

Invert match (lines that DON'T match):

grep -v "DEBUG" log.txt

Filters out all the debug noise.

Count matches:

grep -c "error" log.txt

Just the number. "You have 47 errors. Good luck."

Context around matches:

grep -A 2 "error" log.txt    # 2 lines After
grep -B 2 "error" log.txt    # 2 lines Before
grep -C 2 "error" log.txt    # 2 lines of Context (both)

See what happened around the error.

grep + Regex

grep understands regular expressions:

grep "^error" log.txt         # Lines starting with "error"
grep "error$" log.txt         # Lines ending with "error"
grep "err.r" log.txt          # . matches any character
grep -E "error|warning" log.txt  # error OR warning

The -E flag enables extended regex - more features, less escaping.

Searching Multiple Files

grep "TODO" .js              # All .js files here
grep -r "TODO" src/           # Recursive through src/

The -r flag searches directories recursively.

grep in Pipelines

grep is often the first filter in a chain:

cat log.txt | grep "error" | awk '{print $1}'

Find errors, then extract the first column.

Or filter any command's output:

ps aux | grep "node"

Quick Reference

| What you want | Command | |---------------|---------| | Basic search | grep "pattern" file | | Case-insensitive | grep -i "pattern" file | | Line numbers | grep -n "pattern" file | | Invert match | grep -v "pattern" file | | Count matches | grep -c "pattern" file | | Context | grep -C 3 "pattern" file | | Recursive | grep -r "pattern" dir/ | | OR patterns | grep -E "this\|that" file |

Practice

grep is your constant companion in CTF challenges. Log analysis, config hunting, flag extraction - it all starts with grep.


If you learn one command from this wiki, make it grep. It's the flashlight you'll reach for every single time.*