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: