hlcolor 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/env perl
  2. #
  3. # Author: Jue Ruan
  4. #
  5. use strict;
  6. my $color = 35;
  7. my %fg_color_map = (black=>30, red=>31, green=>32, yellow=>33, blue=>34, magenta=>35, cyan=>36);
  8. my @pats = ();
  9. foreach my $pat (@ARGV){
  10. if($pat=~/^(\S+)=(\S+?)$/){
  11. if(exists $fg_color_map{$2}){
  12. $color = $fg_color_map{$2};
  13. push(@pats, [$1, $color]);
  14. } else {
  15. print STDERR "[hlcolor] unknown color \"$2\"\n";
  16. push(@pats, [$1, $color]);
  17. }
  18. } else {
  19. push(@pats, [$pat, $color]);
  20. }
  21. }
  22. $| = 1;
  23. while(<STDIN>){
  24. foreach my $pat (@pats){
  25. s/($pat->[0])/\e[1;$pat->[1]m\1\e[0m/g;
  26. }
  27. print;
  28. }
  29. 1;
  30. =pod
  31. function highlight() {
  32. declare -A fg_color_map
  33. fg_color_map[black]=30
  34. fg_color_map[red]=31
  35. fg_color_map[green]=32
  36. fg_color_map[yellow]=33
  37. fg_color_map[blue]=34
  38. fg_color_map[magenta]=35
  39. fg_color_map[cyan]=36
  40. fg_c=$(echo -e "\e[1;${fg_color_map[$2]}m")
  41. c_rs=$'\e[0m'
  42. sed -u "s/$1/$fg_c\0$c_rs/g"
  43. }
  44. if [ -z $1 ]; then
  45. echo "Usage: $0 <sed_regex_pattern> <color:black,red,green,yellow,blue,magenta,cyan>"
  46. exit
  47. fi
  48. PAT=$1
  49. COLOR=$2
  50. if [ -z $COLOR ]; then
  51. COLOR=magenta
  52. fi
  53. highlight $PAT $COLOR
  54. =cut