Advertisement
devinteske

colorize() -- sometimes you need more than grep --color

Aug 18th, 2015
490
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 0.59 KB | None | 0 0
  1. # colorize [-c ANSI] pattern
  2. #
  3. # Colorize text matching pattern with ANSI sequence (default is `31;1' for red-
  4. # bold). Non-matching lines are printed as-is.
  5. #
  6. colorize()
  7. {
  8.     local OPTIND=1 OPTARG flag
  9.     local ansi_color=
  10.  
  11.     while getopts c: flag; do
  12.         case "$flag" in
  13.         c) ansi_color="$OPTARG" ;;
  14.         esac
  15.     done
  16.     shift $(( $OPTIND - 1 ))
  17.  
  18.     awk -v color="${ansi_color:-31;1}" -v pattern="$1" '
  19.         (match($0, pattern) && $0 = sprintf("%s%c[%sm%s%c[0m%s",
  20.             substr($0, 0, RSTART - 1), 27, color,
  21.             substr($0, RSTART, RLENGTH), 27,
  22.             substr($0, RSTART + RLENGTH))) || 1
  23.     ' # END-QUOTE
  24. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement