-1

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.

anubhava
  • 761,203
  • 64
  • 569
  • 643
nadapez
  • 2,603
  • 2
  • 20
  • 26

1 Answers1

2

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
anubhava
  • 761,203
  • 64
  • 569
  • 643