DEV Community

Marco Kamner
Marco Kamner

Posted on • Originally published at blog.marco.ninja on

Colorize pattern on CLI

Colorize a pattern in the given input using a neat regex and colorization hack in grep ($ matching all lines but not being able to be highlighted).

color () {
  # Color highlight the pattern in the incoming stream, writing to stdout
  # This effectively matches our PATTERN any "$" (lines end character)
  # But only our PATTERN can be highlighted, line end characters aren't actually there to be highlighted
  local PATTERN=$1

  if [-z "$1"]; then
    echo "Usage: color <pattern>"
    echo "Description: Greps input with --color=always -E 'PATTERN|\$' "
    echo "Example: echo \"hello world\" | color \"world\""
    return 1

  fi
  grep --color=always "$PATTERN\|\$"
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)