printf的字段宽度不支持多字节字符? [英] printf field width doesn't support multibyte characters?
问题描述
我要的printf计算字段宽度时,使正确的列排队...我无法找到答案这个问题,并想知道是否有人在这里有任何建议,或者一个函数来识别多字节字符/脚本,需要这个问题的照顾。
下面是一个快速和肮脏的例子:
printf的##%的5S%5S%5秒## \\ n ##%5S%5S%5秒## \\ N'''*'''''•''
> ## * ##
> ##•##
显然,我想要的结果:
> ## * ##
> ##•##
任何方式实现这一目标?
我可能会使用GNU AWK:
的awk'BEGIN {printf的##%的5S%5S%5秒## \\ n ##%5S%5S%5秒## \\ n,,* ,,,•,}
## * ##
##•##
您甚至可以编写shell awk的顶部所谓的printf函数的包装,以保持相同的接口:
tr2awk(){
FMT =$ 1
回声-n的gawk'BEGIN {printf的\\$ FMT \\
转移
在$ @ARG
做回声-n,\\$ ARG \\
DONE
回声}'
}
,然后覆盖的printf用简单的功能:
的printf(){EVAL`tr2awk$ @`; }
测试吧:
#车printf的二进制测试:
在/ usr /斌/ printf的##%的5S%5S%5秒## \\ n ##%5S%5S%5秒## \\ N'''*'''''•''
## * ##
##•##
#车printf的外壳builin测试:
内置的printf##%的5S%5S%5秒## \\ n ##%5S%5S%5秒## \\ N'''*'''''•''
## * ##
##•###固定printf函数测试:
printf的##%的5S%5S%5秒## \\ n ##%5S%5S%5秒## \\ N'''*'''''•''
## * ##
##•##
I want printf to recognize multi-byte characters when calculating the field width so that columns line up properly... I can't find an answer to this problem and was wondering if anyone here had any suggestions, or maybe a function/script that takes care of this problem.
Here's a quick and dirty example:
printf "## %5s %5s %5s ##\n## %5s %5s %5s ##\n" '' '*' '' '' "•" ''
>## * ##
>## • ##
Obviously, I want the result:
>## * ##
>## • ##
Any way to achieve this?
I will probably use GNU awk:
awk 'BEGIN{ printf "## %5s %5s %5s ##\n## %5s %5s %5s ##\n", "", "*", "", "", "•", "" }'
## * ##
## • ##
You can even write shell wrapper function called printf on top of awk to keep same interface:
tr2awk() {
FMT="$1"
echo -n "gawk 'BEGIN{ printf \"$FMT\""
shift
for ARG in "$@"
do echo -n ", \"$ARG\""
done
echo " }'"
}
and then override printf with simple function:
printf() { eval `tr2awk "$@"`; }
Test it:
# buggy printf binary test:
/usr/bin/printf "## %5s %5s %5s ##\n## %5s %5s %5s ##\n" '' '*' '' '' "•" ''
## * ##
## • ##
# buggy printf shell builin test:
builtin printf "## %5s %5s %5s ##\n## %5s %5s %5s ##\n" '' '*' '' '' "•" ''
## * ##
## • ##
# fixed printf function test:
printf "## %5s %5s %5s ##\n## %5s %5s %5s ##\n" '' '*' '' '' "•" ''
## * ##
## • ##
这篇关于printf的字段宽度不支持多字节字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!