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:
grep + sedThis approach uses grep to find matching lines and sed to highlight only the first occurrence of the pattern in each line.
bashgrep --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)."pattern" with your search term.grep + awkIf you prefer awk, you can use it to highlight only the first occurrence:
bashgrep --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.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:
bashgrep -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.
~/.bashrcTo make this reusable, add an alias to your ~/.bashrc or ~/.bash_aliases:
bashalias grep_first='grep --color=never "$1" | sed "s/$1/\o033[01;31m&\o033[00m/"'
Then run:
bashsource ~/.bashrc
Usage:
bashgrep_first "pattern" file.txt
Vibe can make mistakes. Check answers. Learn more