How to print awk's results with different colors for different fields?

我怕爱的太早我们不能终老 提交于 2019-11-30 06:44:13

To get color output from awk, you can use this approach.

function red(s) {
    printf "\033[1;31m" s "\033[0m "
}

function green(s) {
    printf "\033[1;32m" s "\033[0m "
}

function blue(s) {
    printf "\033[1;34m" s "\033[0m "
}

{
    print red($1), green($2), blue($3)
}

An alternative to using awk functions is passing the colors in shell variables. E.g.

RED='\033[01;31m'
GREEN='\033[01;32m'
YELLOW='\033[01;33m'
BLUE='\033[01;34m'
NONE='\033[0m'

echo "Col1 Col2 Col3 Col4" | \
awk -v r=$RED -v y=$YELLOW -v g=$GREEN -v b=$BLUE -v n=$NONE \
 '{printf r$1n y$2n g$3n b$4n "\n"}'
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!