Search code examples
regexlinuxgrephighlight

grep: highlight only first match of each line when using --color


When I make grep highlight the matches like this:

echo hello hello | grep --color "hello"

I get highlighted all matches in the line, which in the above case is all the line:

hello hello

How can I get highlighted only the first ocurrence:

hello hello

I suppose I can do it with a complex regex but I wonder if there a simpler solution.


Solution

  • It can be easily done using sed:

    sed 's/hello/\x1b[31m&\x1b[0m/' file
    

    This will only color first match of hello word in each line. In replacement we are putting matched word back using & surrounded with escape code for color red.

    Similarly you can do this in awk as well:

    awk '{sub(/hello/, "\x1b[31m&\x1b[0m")} 1' file