Shell Commands

grep for Linux Systems Administrators

Maximilian B. 2 min read 5,252 views

grep: Your First Line of Defense

When a server is misbehaving, logs are exploding, and the phone is ringing — grep is the tool that cuts through the noise. It searches files for lines matching a pattern and is arguably the most-used command in any sysadmin's arsenal.

Basic Usage

# Search for a string in a file
grep "error" /var/log/syslog

# Case-insensitive search
grep -i "warning" /var/log/messages

# Show line numbers
grep -n "failed" /var/log/auth.log

# Count matches
grep -c "404" /var/log/nginx/access.log

# Show only filenames with matches
grep -l "password" /etc/*.conf

# Recursive search through directories
grep -r "listen 80" /etc/nginx/

Essential Flags Every Admin Needs

# Context: lines before (-B), after (-A), or around (-C) match
grep -B 3 -A 3 "OOM" /var/log/kern.log
grep -C 5 "segfault" /var/log/messages

# Invert match (show lines that DON'T match)
grep -v "^#" /etc/ssh/sshd_config    # Show non-comment lines
grep -v "^$" /etc/fstab              # Show non-empty lines

# Extended regex (-E) or Perl regex (-P)
grep -E "error|warning|critical" /var/log/syslog
grep -P "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" access.log

# Match whole words only
grep -w "root" /etc/passwd    # Matches "root" not "chroot"

# Binary file handling
grep -a "string" binary_file         # Treat as text
grep --binary-files=without-match    # Skip binary files

Real-World Sysadmin Recipes

# Find failed SSH login attempts
grep "Failed password" /var/log/auth.log | tail -20

# Extract IP addresses from logs
grep -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b" access.log | sort | uniq -c | sort -rn

# Find all listening ports in configs
grep -rn "listen" /etc/nginx/ /etc/apache2/

# Check for insecure permissions in sudoers
grep -v "^#\|^$" /etc/sudoers

# Monitor logs in real-time for errors
tail -f /var/log/syslog | grep --line-buffered -i "error"

# Find large files mentioned in logs
grep -oP "(?<=File )[^\s]+" /var/log/app.log | xargs ls -lh 2>/dev/null

# Search compressed log files
zgrep "error" /var/log/syslog.*.gz

Performance Tips

Master grep and you'll solve problems in seconds that others spend minutes on. It's not glamorous, but it's the backbone of effective Linux administration.

Share this article
X / Twitter LinkedIn Reddit