On Debian 13 how to make `grep` output as many lines with a single highlighted occurrence for lines with multiple occurrences?
Aug 14, 9:30pm

On Debian 13 (or any Linux system using GNU grep), you can use the --color option to highlight matches, but by default, it highlights all occurrences of the pattern in a line. If you want to highlight only the first occurrence of the pattern in each line, you can use a combination of grep and sed or awk.

Here’s how to do it:


Method 1: Using grep + sed

This approach uses grep to find matching lines and sed to highlight only the first occurrence of the pattern in each line.

bash
grep --color=never "pattern" file.txt | sed "s/pattern/\o033[01;31m&\o033[00m/"
  • --color=never: Disables grep's built-in coloring.
  • sed: Replaces the first occurrence of pattern with an ANSI escape code for red color (\o033[01;31m starts red, \o033[00m resets).
  • Replace "pattern" with your search term.

Method 2: Using grep + awk

If you prefer awk, you can use it to highlight only the first occurrence:

bash
grep --color=never "pattern" file.txt | awk '{sub("pattern", "\033[01;31m&\033[00m"); print}'
  • sub() replaces only the first occurrence of pattern with the ANSI color codes.

Method 3: Using grep with -o and head (for single matches per line)

If you want to show only the first match per line (not the entire line), you can use:

bash
grep -o "pattern" file.txt | head -n 1
  • -o: Outputs only the matching part.
  • head -n 1: Limits to the first match.

However, this won’t show the full line context. To show the full line with only the first match highlighted, stick with Method 1 or 2.


Permanent Solution: Alias in ~/.bashrc

To make this reusable, add an alias to your ~/.bashrc or ~/.bash_aliases:

bash
alias grep_first='grep --color=never "$1" | sed "s/$1/\o033[01;31m&\o033[00m/"'

Then run:

bash
source ~/.bashrc

Usage:

bash
grep_first "pattern" file.txt

Aug 14, 9:30pm

This is a shared conversation and may include unverified content that doesn't reflect Mistral AI's views. Login to resume chatting.

Vibe can make mistakes. Check answers. Learn more