2011-03-23 73 views
55

当这样写的,它以蓝色文本输出:使用颜色与printf的

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

但我想有printf中定义的格式:

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

现在,我已经尝试了几种方案如何添加颜色,没有成功:

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

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

回答

49

您正在将各部分混合在一起,而不是干净地将它们分开。

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

基本上,把固定填充的格式和参数中的可变填充。

+0

谢谢您answear。不知道,字符长度格式必须放在颜色属性之间。 – 2011-03-23 23:17:24

+0

这种格式的方式(这对我来说是新的)。这都是这个标准吗? – Chani 2014-11-25 11:38:36

17

这个工作对我来说:

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 
126

而不是使用过时的终端代码,我建议以下替代。它不仅提供更多可读的代码,而且还允许您将颜色信息与格式说明符分开,就像您原先的想法一样。

blue=$(tput setaf 4) 
normal=$(tput sgr0) 

printf "%40s\n" "${blue}This text is blue${normal}" 

见我的回答HERE为其他颜色

+1

//,这也使得我不必记录代码的含义。我认为这将帮助我们的团队将文字视为文档。 – 2017-05-10 20:55:04

12

这是一个小程序,以获取有关终端不同的颜色。

#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; 
} 
+1

这是c而不是bash。 – eav 2017-09-05 09:58:45

-1
#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; 
} 
+0

问题是关于* printf *在Bash中,而不是C. – cpburnz 2016-07-20 14:40:12

3

这是打印使用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";