在 Bash 中着色非彩色文本 [英] Coloring not colored text in Bash

查看:18
本文介绍了在 Bash 中着色非彩色文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须为文本中的一些单词着色,这很好用,但是当它已经着色时我遇到了问题.当它上色时,我不想再用不同的颜色给它上色.我的问题是我的代码再次着色,即使它已经着色.

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 color. My problem is that my code color it again even if it is already colored.

这是我的代码:

var=$(echo -e $line | grep ".*[^m]${word}[^][^e].*" | sed -e "s/${word}/${color}${word}${endColor}/g")
if(var -n);then
line=$var
f

<小时>

这是一个脚本,其中的颜色很奇怪,甚至是您想要着色的单词.问题是当有一个已经着色的单词并且我不想重新着色时.输入可以是任何东西


Its a script where is every odd the color and even is word you want to color. The problem is when there is a word that is already colored and I dont want to recolore it. Input could be anything

这是完整的代码

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
radek=$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(var -n);then
line=$var
fi
else
color=""
GetColor "$i"

fi
let "a += 1"
done

echo -e $line
exit
done

感谢帮助

推荐答案

这是我的版本,但我刚刚使脚本运行没有错误.我不确定是什么问题,但是已经着色的单词的颜色没有改变.

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.

我怀疑

if(var -n);then

我更正了

  if [ -n "$var" ]; then

这是脚本

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

这篇关于在 Bash 中着色非彩色文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆