在printf中使用颜色

当这样写时,它以蓝色输出文本:

printf "\e[1;34mThis is a blue text.\e[0m" 

但是我想要在printf中定义格式:

 printf '%-6s' "This is text" 

现在我已经尝试了几个select如何添加颜色,但没有成功:

 printf '%-6s' "\e[1;34mThis is text\e[0m" 

我甚至试图添加属性代码格式化,但没有成功。 这不起作用,我找不到任何地方的例子,其中颜色被添加到printf,它已经定义了格式,在我的情况。

你把这些零件混合在一起,而不是干净地把它们分开。

 printf '\e[1;34m%-6s\e[m' "This is text" 

基本上,把固定的东西在格式和variables的东西在参数中。

而不是使用古老的terminal代码,我可以build议下面的select。 它不仅提供了更多可读的代码,而且还允许您将颜色信息与格式说明符分开,就像您最初的想法一样。

 blue=$(tput setaf 4) normal=$(tput sgr0) printf "%40s\n" "${blue}This text is blue${normal}" 

看到我的答案在这里额外的颜色

这适用于我:

 printf "%b" "\e[1;34mThis is a blue text.\e[0m" 

来自printf(1)

 %b ARGUMENT as a string with '\' escapes interpreted, except that octal escapes are of the form \0 or \0NNN 

这是一个在terminal上获得不同颜色的小程序。

 #include <stdio.h> #define KNRM "\x1B[0m" #define KRED "\x1B[31m" #define KGRN "\x1B[32m" #define KYEL "\x1B[33m" #define KBLU "\x1B[34m" #define KMAG "\x1B[35m" #define KCYN "\x1B[36m" #define KWHT "\x1B[37m" int main(){ printf("%sred\n", KRED); printf("%sgreen\n", KGRN); printf("%syellow\n", KYEL); printf("%sblue\n", KBLU); printf("%smagenta\n", KMAG); printf("%scyan\n", KCYN); printf("%swhite\n", KWHT); printf("%snormal\n", KNRM); return 0; } 

这是一个使用bash脚本打印彩色文本的小函数。 您可以添加任意数量的样式,甚至可以打印制表符和换行符:

 #!/bin/bash # prints colored text print_style () { if [ "$2" == "info" ] ; then COLOR="96m"; elif [ "$2" == "success" ] ; then COLOR="92m"; elif [ "$2" == "warning" ] ; then COLOR="93m"; elif [ "$2" == "danger" ] ; then COLOR="91m"; else #default color COLOR="0m"; fi STARTCOLOR="\e[$COLOR"; ENDCOLOR="\e[0m"; printf "$STARTCOLOR%b$ENDCOLOR" "$1"; } print_style "This is a green text " "success"; print_style "This is a yellow text " "warning"; print_style "This is a light blue with a \t tab " "info"; print_style "This is a red text with a \n new line " "danger"; print_style "This has no color"; 
 #include <stdio.h> //fonts color #define FBLACK "\033[30;" #define FRED "\033[31;" #define FGREEN "\033[32;" #define FYELLOW "\033[33;" #define FBLUE "\033[34;" #define FPURPLE "\033[35;" #define D_FGREEN "\033[6;" #define FWHITE "\033[7;" #define FCYAN "\x1b[36m" //background color #define BBLACK "40m" #define BRED "41m" #define BGREEN "42m" #define BYELLOW "43m" #define BBLUE "44m" #define BPURPLE "45m" #define D_BGREEN "46m" #define BWHITE "47m" //end color #define NONE "\033[0m" int main(int argc, char *argv[]) { printf(D_FGREEN BBLUE"Change color!\n"NONE); return 0; }