Coloring not colored text in Bash

前端 未结 1 1126
情歌与酒
情歌与酒 2021-01-16 23:13

I have to colorize some words in the text, that works good, but I have a problem when its already colored. When its colored I dont want to colour it again with different col

相关标签:
1条回答
  • 2021-01-17 00:02

    This is my version, but I've just made the script run without errors. I'm not sure what the problem is, but the colour of already coloured words are not changed.

    I suspect

    if(var -n);then
    

    I corrected it to

      if [ -n "$var" ]; then
    

    Here's the script

    function GetColor {
    if [ $1 == 'r' ];then
    color=$red;
    fi
    if [ $1 == 'b' ];then
    color=$blue;
    fi
    if [ $1 == 'g' ];then
    color=$green;
    fi
    }
    
    red=$'\e[31m'
    green=$'\e[32m'
    blue=$'\e[34m'
    endColor=$'\e[0m'
    a=0
    color=""
    word=""
    while read input
    do
      line=$input
      for i in $*; do
        if (( a% 2 )); then
          word=$i
          var=$(echo -e $line | grep ".*[^m]${word}[^\][^e].*" | sed -e "s/${word}/${color}${word}${endColor}/g")
          if [ -n "$var" ]; then
            line=$var
          fi
        else
          color=""
          GetColor "$i"
        fi
        let "a += 1"
      done
    
      echo -e $line
      exit
    done
    
    0 讨论(0)
提交回复
热议问题