在文本bash中着色的单词

时间:2014-04-20 23:12:03

标签: bash text colors sed

我是Linux初学者。我在文字中填写单词有问题。

red="\033[31m"
green="\033[31m"
blue="\033[34m"
endColor="\033[0m"

line=$(echo -e $input | sed -e "s/${word}/\ ${red} \ ${word} \n \${endColor}/g")
echo $line
in the standard output is this instead of red colored "word"
>> sdngasf 033[31m word n ${endColor}sdaadmfuw

任何人都可以帮我解决这个问题,谢谢

2 个答案:

答案 0 :(得分:1)

也许您应该使用$'\ e ...'而不是“\ 033”

input="hello stack overflow"
word=stack

red=$'\e[31m'
green=$'\e[31m'
blue=$'\e[34m'
endColor=$'\e[0m'

line=$(echo -e $input | sed -e "s/${word}/${red}${word}${endColor}/g")
echo $line

这将输出带有红色“堆栈”的“hello stack overflow”。

答案 1 :(得分:0)

在今天的许多系统中,你可以在bash中使用256种颜色 要了解如何格式化输出,请测试此程序:

cat color_test.sh
#!/bin/bash
#
# generates an 8 bit color table (256 colors) for reference,
# using the ANSI CSI+SGR \e[48;5;${val}m for background and
# \e[38;5;${val}m for text (see "ANSI Code" on Wikipedia)
#
echo -en "\n   +  "
for i in {0..35}; do
        printf "%2b " $i
done
printf "\n\n %3b  " 0
for i in {0..15}; do
echo -en "\e[48;5;${i}m  \e[m "
done

for i in {0..6}; do
        i=$((i*36 +16))
        printf "\n\n %3b  " $i
        for j in {0..35}; do
                val=$((i+j))
                echo -en "\e[48;5;${val}m  \e[m "
        done
done
echo -e "\n"