Jer*_*rin 80 linux bash printf colors
像这样写,它输出蓝色文字:
printf "\e[1;34mThis is a blue text.\e[0m"
Run Code Online (Sandbox Code Playgroud)
但是我希望在printf中定义格式:
printf '%-6s' "This is text"
Run Code Online (Sandbox Code Playgroud)
现在我尝试了几种如何添加颜色的选项,但没有成功:
printf '%-6s' "\e[1;34mThis is text\e[0m"
Run Code Online (Sandbox Code Playgroud)
我甚至试图将格式添加到格式但没有成功.这不起作用,我找不到任何一个例子,其中颜色被添加到printf,其中已定义格式,如我的情况.
Sie*_*geX 155
我可以建议以下替代方案,而不是使用过时的终端代码.它不仅提供更易读的代码,而且还允许您将颜色信息与格式说明符分开,就像您最初预期的那样.
blue=$(tput setaf 4)
normal=$(tput sgr0)
printf "%40s\n" "${blue}This text is blue${normal}"
Run Code Online (Sandbox Code Playgroud)
见我的回答这里的其他颜色
gee*_*aur 70
您将这些部件混合在一起,而不是将它们干净地分开.
printf '\e[1;34m%-6s\e[m' "This is text"
Run Code Online (Sandbox Code Playgroud)
基本上,将固定的东西放在格式中,将变量填入参数中.
Vla*_*lad 28
这对我有用:
printf "%b" "\e[1;34mThis is a blue text.\e[0m"
Run Code Online (Sandbox Code Playgroud)
来自printf(1):
Run Code Online (Sandbox Code Playgroud)%b ARGUMENT as a string with '\' escapes interpreted, except that octal escapes are of the form \0 or \0NNN
小智 17
这是一个在终端上获得不同颜色的小程序.
#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;
}
Run Code Online (Sandbox Code Playgroud)
Ari*_*sta 13
这是一个使用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";
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
104773 次 |
| 最近记录: |