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에 색상을 추가한 예를 찾을 수 없습니다.
구식 단말 코드를 사용하는 것이 아니라, 다음과 같은 대안을 제안합니다.보다 읽기 쉬운 코드를 제공할 뿐만 아니라 원래 의도한 대로 색상 정보를 형식 지정자에서 분리할 수 있습니다.
blue=$(tput setaf 4)
normal=$(tput sgr0)
printf "%40s\n" "${blue}This text is blue${normal}"
기타 색상은 이쪽에서 답변을 참조해 주세요.
부품을 깨끗하게 분리하는 것이 아니라 함께 섞는 것이다.
printf '\e[1;34m%-6s\e[m' "This is text"
기본적으로 고정된 것을 포맷으로, 가변적인 것을 파라미터에 넣습니다.
이것으로 충분합니다.
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가지로 스크립트가 기능하는 경우는, 거의 어디에서라도 휴대할 수 있습니다.
의 최신 실장printf
에dash
[1] 출력은 컬러화되지 않습니다.%s
ANSI 이스케이프 문자를 사용한 형식 지정자\e
-- 단, 포맷 지정자%b
8진법과 조합한\033
(ASCII와 동등)ESC
)가 작업을 완료합니다.이상치에 대해 코멘트해 주세요.그러나 AFAIK, 모든 셸이 구현되었습니다.printf
ASCII 옥탈서브셋을 최소한 사용합니다.
"프린트에 색상 사용"이라는 질문의 제목에 대해 포맷을 설정하는 가장 편리한 방법은 다음을 조합하는 것입니다.%b
포맷 지정자printf
(@Vlad의 이전 답변에서 참조) 8진수 이스케이프를 사용합니다.\033
.
휴대용 컬러쉿
#/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"
출력:
$ ./portable-color.sh
-> This is \033[1;34m blue \033[0m text
-> This is blue text
...그리고 두 번째 줄의 '파란색'은 파란색입니다.
%-6s
OP 형식 지정자는 시작 및 종료 제어 문자 시퀀스 사이의 형식 문자열 중간에 있습니다.
[1] 참조: 섹션 "Builtins" :: "printf" :: "Format"
color() {
STARTCOLOR="\e[$2";
ENDCOLOR="\e[0m";
export "$1"="$STARTCOLOR%b$ENDCOLOR"
}
color info 96m
color success 92m
color warning 93m
color danger 91m
printf $success'\n' "This will be green";
모든 색상이 표시됩니다.색상을 사용할 수 없는 경우 폴백 방법을 사용할 수 있습니다.다음과 같이 쓸 수 있습니다.
printf ${danger:-'%b'}'\n' "This will be red and would not break if color is unavailable";
또는 여러 줄에 걸쳐 메시지를 작성하려면 '\n'을 생략하십시오.
printf $info "This is ";
printf $info "blue!";
printf '\n'
#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' 카테고리의 다른 글
Excel 탭 시트 이름과Visual Basic 시트 이름 (0) | 2023.04.13 |
---|---|
서버에 저장하지 않고 FileUpload Control을 사용하여 업로드된 Excel 파일을 읽습니다. (0) | 2023.04.13 |
콘솔에서 Rails SQL 로깅 사용 안 함 (0) | 2023.04.13 |
UIImageView 이미지 변경 시 페이드/해체 (0) | 2023.04.13 |
PowerShell 스크립트 종료 (0) | 2023.04.08 |