【发布时间】:2020-01-03 00:42:12
【问题描述】:
使用 tput 会更改字符串的长度,因此列不对齐。如何解决这个问题?
在 bash 脚本中尝试了以下代码。
B="$(tput bold)" # Bold text
N="$(tput sgr0)" # Normal text
function testing(){
IN="KEYS | VALUES | DESCRIPTION
id | ${B}10${N} or ${B}20${N} | Enter ID. Default is ${B}10${N}.
status | ${B}true${N} or ${B}false${N} | Enter status of something. Default is ${B}true${N}.
style | Example: Standard | Give suitable standard."
IFS=
while read -r lines; do
IFS='|' read -r -a array <<< "$lines"
printf "%-35s %-35s %-s\n" "${array[0]}" "${array[1]}" "${array[2]}"
done <<< "$IN"
read -p "$*"
exit 0
}
输出类似于:
KEYS VALUES DESCRIPTION
id **10** or **20** Enter ID. Default is **10**.
status **true** or **false** Enter status of something. Default is **true**.
style Example: Standard Give suitable standard.
预计是:
KEYS VALUES DESCRIPTION
id **10** or **20** Enter ID. Default is **10**.
status **true** or **false** Enter status of something. Default is **true**.
style Example: Standard Give suitable standard.
【问题讨论】:
-
当我在我的 bash 环境中运行代码时,我发现 2 个有问题的
DESCRIPTION字符串失去了 20 个缩进空格; vars (${#B}&${#N}) 的长度分别为 4 和 6 个字符;这些变量在VALUES字段中出现两次,总共有 20 个(不可打印)字符;printf/%s将 20 个不可打印的字符计为输出的一部分,因此出现 20 个空格“丢失”(即,printfis 打印 35 个字符......只是其中的 20 个这些字符是非打印的); “呃,马克!” ?我不知道的是:printf是否有一个标志可以忽略不可打印的字符以用于格式目的?
标签: bash formatting printf tput