Linux awk 为文本添加颜色代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14482101/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 18:46:44  来源:igfitidea点击:

awk adding color code to text

linuxbashshellawk

提问by user1745860

awk -F: '{ printf  "%-3s %-2s","\n"  ; }'

How do i add in color code? '\e[1;32m'

我如何添加颜色代码?'\e[1;32m'

I try adding in to printf, it give me output of the string instead of color code..

我尝试添加到 printf 中,它给了我字符串的输出而不是颜色代码..

'\e[1;32m' .......

回答by chepner

awkdoesn't recognize '\e' as a code for the escape character. Here's a workaround (something more elegant may exist):

awk不识别 '\e' 作为转义字符的代码。这是一种解决方法(可能存在更优雅的方法):

# Decimal 27 is the ASCII codepoint for the escape character
awk '{ printf "%c[1;32m foo\n", 27 }' <<<foo

回答by Kent

 awk 'BEGIN{print "^[[1;33mYELLOW"}' 

would print string YELLOW in yellow (color)

将以黄色(颜色)打印字符串 YELLOW

NOTEthe first ^[you have to type ctrl-vthen ESC

注意首先^[你必须输入ctrl-v然后ESC

I would add a screen shot to show.

我会添加一个屏幕截图来显示。

enter image description here

在此处输入图片说明

the above screenshot showed it worked under zsh and bash.

上面的截图显示它在 zsh 和 bash 下工作。

回答by ?οδεMεδι?

Hope this helps anyone looking for an answer!

希望这可以帮助任何寻找答案的人!

As you can see, the functions and various initialization makes it possible to write quite a simple print line as below.

如您所见,函数和各种初始化使得编写如下所示的非常简单的打印行成为可能。

print colour("Red")colour("Blue")
colour( <attribute> , <background-colour> , <foreground-colour> )
colour( <background-colour> , <foreground-colour> )
colour( <foreground-colour> )
colour("None");

For the colourfunction, you may either pass in the integer value of colour or the name. It takes params in the below formats.

对于colour函数,您可以传入颜色的整数值或名称。它采用以下格式的参数。

function isnumeric(x)
{
    return ( x == x+0 );
}

function name_to_number(name, predefined)
{
    if (isnumeric(name))
        return name;

    if (name in predefined)
        return predefined[name];

    return name;
}

function colour(v1, v2, v3)
{
    if (v3 == "" && v2 == "" && v1 == "")
        return;

    if (v3 == "" && v2 == "")
        return sprintf("%c[%dm", 27, name_to_number(v1, fgcolours));
    else if (v3 == "")
        return sprintf("%c[%d;%dm", 27, name_to_number(v1, bgcolours), name_to_number(v2, fgcolours));
    else
        return sprintf("%c[%d;%d;%dm", 27, name_to_number(v1, attributes), name_to_number(v2, bgcolours), name_to_number(v3, fgcolours));
}

BEGIN {
    # hack to use attributes for just "None"
    fgcolours["None"] = 0;

    fgcolours["Black"] = 30;
    fgcolours["Red"] = 31;
    fgcolours["Green"] = 32;
    fgcolours["Yellow"] = 33;
    fgcolours["Blue"] = 34;
    fgcolours["Magenta"] = 35;
    fgcolours["Cyan"] = 36;
    fgcolours["White"] = 37;

    bgcolours["Black"] = 40;
    bgcolours["Red"] = 41;
    bgcolours["Green"] = 42;
    bgcolours["Yellow"] = 43;
    bgcolours["Blue"] = 44;
    bgcolours["Magenta"] = 45;
    bgcolours["Cyan"] = 46;
    bgcolours["White"] = 47;

    attributes["None"] = 0;
    attributes["Bold"] = 1;
    attributes["Underscore"] = 4;
    attributes["Blink"] = 5;
    attributes["ReverseVideo"] = 7;
    attributes["Concealed"] = 8;
}

{
    print colour("Red")colour("Blue")
awk 'BEGIN{ print "3[34msomething in colour3[0m";}'
colour("None"); }

You can selectively give the required params.

您可以有选择地提供所需的参数。

echo something | awk '{ print "3[34m"" in colour 3[0m";}'

回答by bartekbrak

\033[?mproperly quoted gives colour:

\033[?m正确引用给出颜色:

BDF()
{
#awk 'BEGIN{ print "3[34msomething in colour3[0m";}'
#bdf $spool $data $sysout ~ /home/fnsonlh  |grep -v avail| awk '{print " ""        "}' | tail -n +2 |tr -d "2"
bdf $spool $data $sysout ~ /home/fnsonlh  |grep -v avail| awk '{if( > 89)
 {
   print "3[0;31m"" ""3[0m      "
  }
 else
 {
  print "3[0;32m"" ""3[0m      "
 }}' |tail -n +2 |tr -d "2"
#"2 is new line caracter"
echo
#/usr/bin/w -u
uptime
}
#[email protected]

notice how one needs to unescape $1below:

请注意$1下面需要如何转义:

echo "line 1
line 2" | awk '/line/ {print "3[32m"  "3[31m"  }'

回答by Nishant Chawre

30 - black   34 - blue          
   31 - red     35 - magenta       
   32 - green   36 - cyan          
   33 - yellow  37 - white     

回答by Eduardo

Try this example:

试试这个例子:

GREENB='3[0;41m'    #Green Background (Color verde de fondo)
GREEN='3[0;32m'     #Green Text (Color verde en el texto
REDB='3[0;41m'      #Red Background (Color rojo de fondo)
RED='3[0;31m'       #Red text (Color rojo en el texto)
NORMALB='3[0;49m'   #Default background (Color por defecto de fondo)
NORMAL='3[0m'       #Default foreground (Color por defecto del texto)

enter image description here

在此处输入图片说明

Color is given by "\033[32m"

颜色由 "\033[32m"

For Colors:

对于颜色:

##代码##

回答by Victor Marrerp

Define two variables or those that you need

定义两个变量或您需要的变量

Example:

例子:

##代码##

awk code : echo "This is a test" | awk -vRojo=${RED} -v NC=${NORMAL} '{print Rojo $1, $2, NC $3, $4}'

awk 代码: echo "This is a test" | awk -vRojo=${RED} -v NC=${NORMAL} '{print Rojo $1, $2, NC $3, $4}'



Color code explanation

色码说明

\e[${ATTRIBUTE};${BACKGROUND_COLOR};${FOREGROUND_COLOR}m

\e[${ATTRIBUTE};${BACKGROUND_COLOR};${FOREGROUND_COLOR}m

Where:

在哪里:

  • \e: <Esc>character (can be \e, \033,\x1B)
  • ${ATTRIBUTE}: Defines the styleof the text (Normal, Bold/Bright, Dim, Underlined, Blink, Reverse, Hidden). 0 is Normal;
  • ${BACKGROUND_COLOR}: Defines the backgroundcolor;
  • ${FOREGROUND_COLOR}: Defines the foregroundcolor;
  • \e:<Esc>字符(可以是\e, \033, \x1B
  • ${ATTRIBUTE}:定义文本的样式NormalBold/BrightDimUnderlinedBlinkReverseHidden)。0 是正常的;
  • ${BACKGROUND_COLOR}:定义背景颜色;
  • ${FOREGROUND_COLOR}:定义前景色


More Info

更多信息

More colors and info on Bash colors here

更多关于 Bash 颜色的颜色和信息在 这里