Intermediate · 10 min · practise every command in the built-in terminal

grep — Search for Patterns

grep searches for text patterns inside files. One of the most used Linux commands.

Basic search

grep 'student' /etc/passwd
grep 'error' /var/log/syslog

Common flags

grep -i 'Error' file.txt      # Case-insensitive
grep -n 'word' file.txt       # Show line numbers
grep -c 'word' file.txt       # Count matching lines
grep -v 'word' file.txt       # Invert: lines that DON'T match
grep -l 'word' *.txt          # List files that match
grep -r 'word' directory/     # Recursive search
grep -w 'word' file.txt       # Match whole words only

Context flags

grep -A 3 'error' file.txt    # 3 lines After match
grep -B 3 'error' file.txt    # 3 lines Before match
grep -C 3 'error' file.txt    # 3 lines Context (both)

Regular expressions

grep '^root' /etc/passwd       # Lines starting with 'root'
grep 'bash$' /etc/passwd       # Lines ending with 'bash'
grep '[0-9]' file.txt          # Lines containing digits
grep -E 'cat|dog' file.txt     # Extended regex: OR

With pipes

ps aux | grep nginx
history | grep ssh

Practice tasks

  1. Search for 'student' in /etc/passwd
  2. Search for lines starting with 'root' in /etc/passwd
  3. Count how many users have /bin/bash as their shell
  4. Find lines in /etc/passwd that do NOT contain 'nologin'
  5. Search case-insensitively for 'ROOT' in /etc/passwd

Commands in this lesson

Reading Files