reekanmantell
reekanmantell

Reputation: 3

Using bash printf right-align second column of text (with colored text)

I am writing a script to automate a bunch of commands, and I want the output to be both right-aligned and colored. So far I am able to get one or the other, but I have been unsuccessful in achieving both. My (testing) script is as follows:

#!/bin/bash

columns=$(tput cols)
txtgrn=$(tput setaf 2) # Green
txtpur=$(tput setaf 5) # Purple
txtrst=$(tput sgr0) # Text reset.

col1="60"
let "col2 = $columns - $col1"


# Colored text, left-aligned
string1="${txtpur}Running update 1${txtrst}"
string2="${txtgrn}(1 of 10)${txtrst}"
printf "%-*s%*s\n" "$col1" "$string1" "$col2" "$string2"

string1="${txtpur}Running update 10${txtrst}"
string2="${txtgrn}(10 of 10)${txtrst}"
printf "%-*s%*s\n" "$col1" "$string1" "$col2" "$string2"


# Non-colored text, right-aligned
string1="Running update 1"
string2="(1 of 10)"
printf "%-*s%*s\n" "$col1" "$string1" "$col2" "$string2"

string1="Running update 10"
string2="(10 of 10)"
printf "%-*s%*s\n" "$col1" "$string1" "$col2" "$string2"

exit 0

I am working on Mac OS 10.7.5 in the standard Mac Terminal program

Upvotes: 0

Views: 2159

Answers (1)

Neil
Neil

Reputation: 55392

string1="Running update 1"
string2="(1 of 10)"
printf "${txtpur}%-*s${txtgrn}%*s${txtrst}\n" "$col1" "$string1" "$col2" "$string2"

string1="Running update 10"
string2="(10 of 10)"
printf "${txtpur}%-*s${txtgrn}%*s${txtrst}\n" "$col1" "$string1" "$col2" "$string2"

Upvotes: 1

Related Questions