简体   繁体   English

使用bash printf将文本的第二列右对齐(带有彩色文本)

[英]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 我正在标准Mac Terminal程序中使用Mac OS 10.7.5

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM