Skip to main content

Formatting & Counting Output

Beyond simply printing matched lines, grep includes flags to format the output, identify the source files, and calculate summary statistics.

1. Line Numbers (-n)

If you are using grep to find code that needs to be fixed, you need to know exactly where in the file the match occurred.

The -n (--line-number) flag prefixes each output line with its 1-based line number.

# Example Output:
# 42: return config_value;
grep -n "return config_value" src/app.c

2. File Names (-H and -h)

When grep searches a single file, it assumes you know the filename, so it only prints the matching text. When it searches multiple files, it automatically prefixes the text with the filename so you know where the match came from.

You can explicitly control this behavior:

  • -H (With filename): Force grep to ALWAYS print the filename, even if searching only one file.
  • -h (No filename): Force grep to NEVER print the filename, even if searching multiple files.
# Output: /etc/fstab:UUID=123...
grep -H "UUID" /etc/fstab

# Output: UUID=123... (No filename)
grep -h "UUID" /etc/fstab /etc/mtab

3. Just Give Me The Filename (-l and -L)

Sometimes you don't care what the matched text is; you just want a list of files that contain the match. This is extremely common when piping files to sed or xargs.

  • -l (Files With Matches): Prints only the names of files containing at least one match. Once it finds a match, it stops reading that file and moves to the next, saving massive amounts of I/O.
  • -L (Files Without Matches): Prints only the names of files that do NOT contain the match.
# Find all config files that contain the word "deprecated"
grep -l "deprecated" /etc/nginx/conf.d/*.conf

4. Counting Matches (-c)

Instead of piping to wc -l to count matches, grep has a built-in counting engine.

The -c (--count) flag suppresses normal output and prints a count of matching lines for each input file.

# Count how many errors occurred today
grep -c "ERROR" /var/log/syslog

Note: -c counts matching lines, not the total number of matches. If the word "ERROR" appears 5 times on a single line, grep -c counts it as 1.

5. Color Highlighting (--color)

To make visually parsing the output easier, you can highlight the specific substring that triggered the match.

grep --color=auto "FATAL" /var/log/syslog

By setting it to auto, grep will colorize the output when printing to the terminal, but safely disable coloring when piping to another file or script (preventing raw ANSI escape codes from corrupting data).