1

I have some ASCII art over multiple lines of a printf command eg:

printf %s '

\    /
 \  /
  \/
'

and I would like to make each line a different colour. I have tried the obvious \e[31m but this doesn't work because I need the printf command to print as a string (%s) and ignore backslashes, because of my ASCII art. I have also tried this:

r="\e1;[31m"
e="\e[0m"

a='\    /'
b=' \  /'
c='  \/'

printf $r%s$e "$a"

with no luck. Is this possible at all? Thank you.

3 Answers 3

1

You can process the output of the printf with a command which applies the color. For example,

printf %s '
\    /
 \  /
  \/
 /  \
/    \
' | awk 'BEGIN{c=0} {printf "\033[3%dm%s\033[0m\n", 1 + c, $0; c = (c + 1) % 6;}'

gives

^[[31m^[[0m
^[[32m^[[0m
^[[33m\    /^[[0m
^[[34m \  /^[[0m
^[[35m  \/^[[0m
^[[36m /  \^[[0m
^[[31m/    \^[[0m

In steps:

  • The printf command sends its output via a pipe (the "|") to the awk script which is given in the single-quotes.
  • In that script, I initialized a counter 'c', using the first chunk in curly braces, after the special keyword "BEGIN" (which is executed once).
  • The second chunk in curly-braces is executed for each line read by awk.
  • awk uses its own printf to print the escape sequence setting color, printing the text and resetting the colors.
  • The "$0" symbol holds the whole line (without the newline).
  • I used an expression to update 'c' after each line ("%" is the modulus operator, making 'c' range from 0 through 5).
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this works well. Would you mind explaining to me exactly what each part of the awk command does? I'm quite new to all this, thank you.
1

You can first store the colors in variables and use them to format the string like this:

#!/bin/bash

RED="\e[0;31m"
GREEN="\e[0;32m"
RESET="\e[0m"

printf "%s $RED%s $GREEN%s $RESET%s\n" BLACK RED GREEN BLACK

Comments

1

This will work:

r='\033[31m'
e='\033[0m'

a='\    /'
b=' \  /'
c='  \/'

printf "$r%s$e\n" "$a" "$b" "$c"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.