The grep command in Linux: searching patterns in text

Introduction

The grep command (Global Regular Expression Print) is one of the most powerful and widely used tools in the Linux command-line environment. It allows searching within files or text streams for any pattern that matches a regular expression, returning only the lines that meet the specified criterion. Its simplicity and speed make it an indispensable ally for system administrators, developers, and any user who needs to filter information quickly.

Basic Syntax

The simplest way to use grep is:

grep [options] pattern file

If no file is specified, grep reads from standard input, allowing it to be chained with other commands via pipes (|). The pattern can be a literal string or a more complex regular expression.

Most Used Options

  • -i: ignores case sensitivity.
  • -v: inverts the match, showing lines that do NOT contain the pattern.
  • -c: counts the number of matching lines.
  • -n: shows the line number along with each match.
  • -r or -R: performs a recursive search in directories.
  • -l: lists only the names of files containing at least one match.
  • -w: matches only whole words.
  • -E: interprets the pattern as an extended regular expression (equivalent to egrep).
  • -F: treats the pattern as a fixed string, not interpreting metacharacters (equivalent to fgrep).

Practical Examples

  • Search for a word in a file:
  • grep 'error' /var/log/syslog
  • Ignore case and show line number:
  • grep -in 'usuario' /etc/passwd
  • Count how many times an IP address appears in a log:
  • grep -c '192\.168\.1\.' access.log
  • Show lines that do NOT contain the word “debug”:
  • grep -v 'debug' aplicación.log
  • Search recursively in all .conf files in a directory:
  • grep -r 'puerto' /etc/nginx/
  • Use extended regular expressions to find dates in YYYY-MM-DD format:
  • grep -E '[0-9]{4}-[0-9]{2}-[0-9]{2}' reporte.txt
  • Show only the names of files that contain the word “TODO”:
  • grep -rl 'TODO' src/

Advanced Tricks

  • Combine with awk or sed: after filtering with grep, the output can be processed with other tools to extract columns or perform substitutions.
  • Use context expressions: -A n (after), -B n (before) and -C n (context) show lines

    This post is also available in ESPAÑOL.

Leave a Reply

Your email address will not be published. Required fields are marked *

Esta obra está bajo una Licencia Creative Commons Atribución 4.0 Internacional para Francesc Roig francesc@vivaldi.net .