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에 색상이 추가되는 예를 찾을 수 없습니다.
부품을 깨끗하게 분리하는 대신 함께 혼합하는 것입니다.
printf '\e[1;34m%-6s\e[m' "This is text"
기본적으로 고정 된 것은 형식에, 변수는 매개 변수에 넣습니다.
구식 터미널 코드를 사용하는 대신 다음 대안을 제안 할 수 있습니다. 더 읽기 쉬운 코드를 제공 할뿐만 아니라 원래 의도 한대로 형식 지정자와 색상 정보를 별도로 유지할 수도 있습니다.
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
이것은 터미널에서 다른 색상을 얻는 작은 프로그램입니다.
#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";
컬러 쉘 출력을 인쇄하기 위해이 c 코드를 사용합니다. 코드는 이 게시물을 기반으로 합니다 .
//General Formatting
#define GEN_FORMAT_RESET "0"
#define GEN_FORMAT_BRIGHT "1"
#define GEN_FORMAT_DIM "2"
#define GEN_FORMAT_UNDERSCORE "3"
#define GEN_FORMAT_BLINK "4"
#define GEN_FORMAT_REVERSE "5"
#define GEN_FORMAT_HIDDEN "6"
//Foreground Colors
#define FOREGROUND_COL_BLACK "30"
#define FOREGROUND_COL_RED "31"
#define FOREGROUND_COL_GREEN "32"
#define FOREGROUND_COL_YELLOW "33"
#define FOREGROUND_COL_BLUE "34"
#define FOREGROUND_COL_MAGENTA "35"
#define FOREGROUND_COL_CYAN "36"
#define FOREGROUND_COL_WHITE "37"
//Background Colors
#define BACKGROUND_COL_BLACK "40"
#define BACKGROUND_COL_RED "41"
#define BACKGROUND_COL_GREEN "42"
#define BACKGROUND_COL_YELLOW "43"
#define BACKGROUND_COL_BLUE "44"
#define BACKGROUND_COL_MAGENTA "45"
#define BACKGROUND_COL_CYAN "46"
#define BACKGROUND_COL_WHITE "47"
#define SHELL_COLOR_ESCAPE_SEQ(X) "\x1b["X"m"
#define SHELL_FORMAT_RESET ANSI_COLOR_ESCAPE_SEQ(GEN_FORMAT_RESET)
int main(int argc, char* argv[])
{
//The long way
fputs(SHELL_COLOR_ESCAPE_SEQ(GEN_FORMAT_DIM";"FOREGROUND_COL_YELLOW), stdout);
fputs("Text in gold\n", stdout);
fputs(SHELL_FORMAT_RESET, stdout);
fputs("Text in default color\n", stdout);
//The short way
fputs(SHELL_COLOR_ESCAPE_SEQ(GEN_FORMAT_DIM";"FOREGROUND_COL_YELLOW)"Text in gold\n"SHELL_FORMAT_RESET"Text in default color\n", stdout);
return 0;
}
man printf.1
하단에 "... 쉘에 자체 버전이있을 수 있습니다."라는 메모가 있습니다 printf
. 이 질문은에 태그가 지정되어 bash
있지만 가능한 경우 모든 쉘에 이식 가능한 스크립트를 작성하려고합니다 . dash
휴대 좋은 최소 기준은 보통 - 대답은 여기에서 작동하므로 bash
, dash
, zsh
. 스크립트가 그 3에서 작동한다면 거의 모든 곳으로 이식 가능합니다.
The latest implementation of printf
in dash
[1] doesn't colorize output given a %s
format specifier with an ANSI escape character \e
-- but, a format specifier %b
combined with octal \033
(equivalent to an ASCII ESC
) will get the job done. Please comment for any outliers, but AFAIK, all shells have implemented printf
to use the ASCII octal subset at a bare minimum.
To the title of the question "Using colors with printf", the most portable way to set formatting is to combine the %b
format specifier for printf
(as referenced in an earlier answer from @Vlad) with an octal escape \033
.
portable-color.sh
#/bin/sh
P="\033["
BLUE=34
printf "-> This is %s %-6s %s text \n" $P"1;"$BLUE"m" "blue" $P"0m"
printf "-> This is %b %-6s %b text \n" $P"1;"$BLUE"m" "blue" $P"0m"
Outputs:
$ ./portable-color.sh
-> This is \033[1;34m blue \033[0m text
-> This is blue text
...and 'blue' is blue in the second line.
The %-6s
format specifier from the OP is in the middle of the format string between the opening & closing control character sequences.
[1] Ref: man dash
Section "Builtins" :: "printf" :: "Format"
#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;
}
참고URL : https://stackoverflow.com/questions/5412761/using-colors-with-printf
'Programing' 카테고리의 다른 글
Android ListView 스크롤 (0) | 2020.10.11 |
---|---|
구분 기호에 따라 문자열을 문자열 배열로 분할 (0) | 2020.10.11 |
사용자 정의 UITableViewCell 선택 스타일? (0) | 2020.10.11 |
ConstraintLayout을 ScrollView 안에 넣을 수 있습니까? (0) | 2020.10.11 |
Mac OS X 10.9에서 pip를 사용하여 Python 이미지 라이브러리를 설치하는 중 오류 발생 (0) | 2020.10.11 |