Este artículo fue publicado originalmente en go2linux.org el 15 de agosto de 2007. El dominio ya no me pertenece, pero soy el autor original. Lo republico aquí en garron.me con correcciones y mejoras.

Introducción

grep es una utilidad para buscar cadenas específicas en archivos, línea por línea. También se pueden usar expresiones regulares en lugar de cadenas simples.

Uso

grep [opciones] patrón [lista-de-archivos]

La salida de grep sin opciones muestra todas las líneas que contienen el patrón en el archivo indicado.

Algunas de sus opciones más útiles son:

-v Invierte el comportamiento de grep y lista las líneas que no contienen el patrón.

-n Muestra la línea donde aparece el patrón (o no aparece, cuando se usa con -v) junto con el número de línea.

-c Muestra la cantidad de líneas que contienen el patrón en el archivo o archivos indicados.

-i Hace que grep ignore mayúsculas y minúsculas, por lo que la búsqueda deja de ser sensible a ellas.

Ejemplos

Dado un archivo grep.txt (la página del manual de grep):

grep -c very grep.txt
1

grep -c in grep.txt
181

grep -i email grep.txt
       Email  bug  reports  to  [email protected].  Be sure to include the

grep -i -n email grep.txt
408:       Email  bug  reports  to  [email protected].  Be sure to include the

También es muy útil para depurar. Si estás intentando encontrar un mensaje de dhcpd en tu archivo /var/log/messages pero hay demasiado ruido, puedes combinarlo con tail:

tail -f /var/log/messages | grep dhcp

Ahora verás en pantalla solo los mensajes que contienen la cadena "dhcp", sin importar cuántos otros mensajes lleguen al archivo de log.

La página del manual

GREP(1)                                                                GREP(1)

NAME
       grep, egrep, fgrep, rgrep - print lines matching a pattern

SYNOPSIS
       grep [options] PATTERN [FILE...]
       grep [options] [-e PATTERN | -f FILE] [FILE...]

DESCRIPTION
       grep  searches the named input FILEs (or standard input if no files are
       named, or the file name - is given) for lines containing a match to the
       given PATTERN.  By default, grep prints the matching lines.

       In addition, three variant programs egrep, fgrep and rgrep are available.
       egrep is the same as grep -E.  fgrep is the same as grep -F.
       rgrep is the same as grep -r.

OPTIONS
       -A NUM, --after-context=NUM
              Print NUM lines of trailing context after matching lines.

       -B NUM, --before-context=NUM
              Print NUM lines of leading context before matching lines.

       -c, --count
              Suppress normal output; instead print a count of matching lines
              for each input file.

       -E, --extended-regexp
              Interpret PATTERN as an extended regular expression.

       -i, --ignore-case
              Ignore case distinctions in both the PATTERN and the input files.

       -l, --files-with-matches
              Suppress normal output; instead print the name of each input file
              that contains a match.

       -n, --line-number
              Prefix each line of output with its line number within its input file.

       -r, --recursive
              Read all files under each directory, recursively.

       -v, --invert-match
              Invert the sense of matching, selecting non-matching lines.

       -w, --word-regexp
              Select only those lines containing matches that form whole words.