简体   繁体   English

linux shell脚本printf数字格式颜色

[英]linux shell script printf number format color

Ahead, Sorry for my english sentence. 提前,抱歉我的英语句子。 ( I am weak at English ) (我英语不好)

Here is a source. 这是来源。
I wanna color the ${test} in %d %f format. 我想以%d%f格式为$ {test}上色。
But I get an error. 但是我得到一个错误。 Invalid number. 无效号码。

I wanna maintain %d %f format ( for comma and point ) and also want the color. 我想保留%d%f格式(用于逗号和point),并且还想要颜色。
Please, know the way. 请知道路。

source 资源

#!/bin/sh
warning_color=$(tput setaf 4) # blue
end_color=$(tput sgr0)

test="30000"
result="30000"
if [[ ${test} -gt 20000 ]]
then
  test="${warning_color}${test}${end_color}"
fi
printf "%'10d%'10d\n" "${test}" "${result}"

test="30000.13"
result="30000.13"
if [[ ${test%%.*} -gt 20000 ]]
then
  test="${warning_color}${test}${end_color}"
fi
printf "%'10.2f%'10.2f\n" "${test}" "${result}"

error ( 30000 and 30000.13 color is blue in error message ) 错误(错误消息中30000和30000.13颜色为蓝色)

a.sh: line 7: printf: 30000: invalid number
     0a.sh: line 11: printf: 30000.13: invalid number
  0.00

You need to add the colours to the format strings, otherwise the numbers are no longer as into or float when you add the color codes to The variables 您需要将颜色添加到格式字符串中,否则当您将颜色代码添加到变量中时,数字不再像数字一样浮动

Ex. 例如

$ blue=$(tput setaf 4)
$ end=$(tput sgr0)
$ val1=3000
$ val2=3000.11
$ printf "$blue %10d $end\n" $val1
        3000
$ printf "$blue %10.2f $end\n" $val2
     3000.11

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

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