如何在 Bash 中右对齐和左对齐文本字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8682592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to right align and left align text strings in Bash
提问by Highway of Life
I'm creating a bash script and would like to display a message with a right aligned status (OK, Warning, Error, etc) on the same line.
我正在创建一个 bash 脚本,并希望在同一行上显示一条具有右对齐状态(正常、警告、错误等)的消息。
Without the colors, the alignment is perfect, but adding in the colors makes the right aligned column wrap to the next line, incorrectly.
没有颜色,对齐是完美的,但是添加颜色会使右对齐的列错误地换行到下一行。
#!/bin/bash
log_msg() {
RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
NORMAL=$(tput sgr0)
MSG=""
let COL=$(tput cols)-${#MSG}
echo -n $MSG
printf "%${COL}s" "$GREEN[OK]$NORMAL"
}
log_msg "Hello World"
exit;
采纳答案by Gordon Davisson
I'm not sure why it'd wrap to the next line -- having nonprinting sequences (the color changes) should make the line shorter, not longer. Widening the line to compensate works for me (and BTW I recommend using printf instead of echo -nfor the actual message):
我不确定为什么它会换行到下一行——具有非打印序列(颜色变化)应该使行更短,而不是更长。加宽补偿线对我有用(顺便说一句,我建议使用 printf 而不是echo -n实际消息):
log_msg() {
RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
NORMAL=$(tput sgr0)
MSG=""
let COL=$(tput cols)-${#MSG}+${#GREEN}+${#NORMAL}
printf "%s%${COL}s" "$MSG" "$GREEN[OK]$NORMAL"
}
回答by chrisaycock
You have to account for the extra space provided by the colors.
您必须考虑颜色提供的额外空间。
log_msg() {
RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
NORMAL=$(tput sgr0)
MSG=""
STATUS="[OK]"
STATUSCOLOR="$GREEN${STATUS}$NORMAL"
let COL=$(tput cols)-${#MSG}+${#STATUSCOLOR}-${#STATUS}
echo -n $MSG
printf "%${COL}s\n" "$STATUSCOLOR"
}

