2011-03-23 45 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";