[英]Linux bash printf format with color assign to variable
I just want a String (including coloring) be formatted by printf command and assign the result to a variable. 我只想用printf命令格式化一个字符串(包括颜色),并将结果分配给一个变量。
Without assigning it to a variable it works fine, but as soon as I assign the result to a variable and write the result, the format is gone. 无需将其分配给变量就可以正常工作,但是一旦我将结果分配给变量并写入结果,格式就消失了。
My example: 我的例子:
RED=$'\033[0;31m'
NC=$'\033[0m'
INPUT="AB${RED}CD${NC}EF"
printf -v OUTPUT '| %-20s | %-25s| %-10s' " $INPUT " " OTHER " " TEST "
echo $OUTPUT
OUTPUT="$(printf '| %-20s | %-25s| %-10s' " $INPUT " " OTHER " " TEST ")"
echo $OUTPUT
OUTPUT=$(printf '| %-20s | %-25s| %-10s' " $INPUT " " OTHER " " TEST ")
echo $OUTPUT
printf '| %-20s | %-25s| %-10s' " $INPUT " " OTHER " " TEST "
echo ""
I found several solutions for passing the result to a variable (-v VARIABLE), but it looses the format. 我发现了几种将结果传递给变量(-v VARIABLE)的解决方案,但是它失去了格式。
Thanks for your help and many greetings, 感谢您的帮助和许多问候,
Hauke 豪克
EDIT 1: Also one problem seems to be the colorcode. 编辑1:还有一个问题似乎是颜色代码。 printf counts AB${RED}CD${NC}EF as 17 characters instead of 6. printf将AB $ {RED} CD $ {NC} EF计数为17个字符,而不是6个字符。
Use this ( echo "$VAR" in "" ) to keep the formatting. 使用它( 在“”中回显“ $ VAR” )保持格式。 The different ways of assigning the variable make no difference: 分配变量的不同方法没有区别:
printf -v OUTPUT '| %-20s | %-25s| %-10s' " $INPUT " " OTHER " " TEST "
# or
OUTPUT=$(printf '| %-20s | %-25s| %-10s' " $INPUT " " OTHER " " TEST ")
echo "$OUTPUT"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.