【问题标题】:Coloring words in text bash在文本 bash 中为单词着色
【发布时间】:2014-06-04 23:59:20
【问题描述】:

我是 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

谁能帮我解决这个问题,谢谢

【问题讨论】:

    标签: bash text colors sed


    【解决方案1】:

    在当今的许多系统中,您可以在 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"
    

    【讨论】:

    【解决方案2】:

    也许你应该使用 $'\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
    

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

    【讨论】:

    • 我不知道为什么你需要-e 选项到echosed,但你绝对应该写"$input""$line",除非你打算放弃换行符、制表符和空格序列,以防它们出现。
    • @rici 您需要echo-e 选项来处理颜色转义。尽管sed 无论如何都破坏了原始语法,但这里并不真正需要。更简单的方法是使用 line="$(echo -e "${input//${word}/${red}${word}${endColor}}")" 替换 bash 字符串,您可以保留 op 原来的颜色变量。
    • @BroSlow:我知道为什么在 OP 中需要它。但这里都不需要。 Fwiw,一个好的答案可以解释为什么会在 sed 中出现问题,以及为什么引用 $line$input 很有用,但遗憾的是,CBA。
    猜你喜欢
    • 2014-06-05
    • 1970-01-01
    • 2018-08-26
    • 1970-01-01
    • 2015-05-16
    • 2014-05-15
    • 2014-03-25
    • 2018-04-03
    • 2019-04-24
    相关资源
    最近更新 更多