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.-ror-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 toegrep).-F: treats the pattern as a fixed string, not interpreting metacharacters (equivalent tofgrep).
Practical Examples
- Search for a word in a file:
grep 'error' /var/log/syslog
grep -in 'usuario' /etc/passwd
grep -c '192\.168\.1\.' access.log
grep -v 'debug' aplicación.log
grep -r 'puerto' /etc/nginx/
grep -E '[0-9]{4}-[0-9]{2}-[0-9]{2}' reporte.txt
grep -rl 'TODO' src/
Advanced Tricks
- Combine with
awkorsed: after filtering withgrep, 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.