我经常在 shell 脚本中使用 printf 来制作一些漂亮的对齐输出
问题是,每次打印的字符串中出现重音 (éèà) 时,它都会将后面的字符串向后移动 1 步。
例子 :
printf "%-10s %s\n" "toto" "test"
printf "%-10s %s\n" "titi" "test"
printf "%-10s %s\n" "tété" "test"
printf "%-10s %s\n" "toto" "test"
预期的 :toto test
titi test
tété test
toto test
得到了 :toto test
titi test
tété test
toto test
有人对此有解释吗,我该怎么做才能使 printf 正确处理特殊字符?感谢您的帮助
最佳答案
Does someone have an explanation on this
é
is character用两个字节编码。what can I do to make printf doing it right with special characters?
设计自己的填充方法,将 utf-8s 考虑在内。理想情况下,我相信像
wprintf
这样的工具或制作 %Ls
格式说明符调用 wcwidth()
确定字符宽度或类似的东西会受到欢迎和有用。到目前为止,至少我的 bash 在计算字符串长度时会考虑 utf-8 字符。您可以自己插入填充:
printf "%-10s %s\n" "titi" "test";
s="tété";
# (echo -n "$s" | wc -c) is 6 , but ${#s} is 4!
printf "%s%*s %s\n" "$s" "$((10-${#s}))" "" "test"
关于bash - 填充的 printf 格式字符串没有使用多字节字符添加足够的填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65006486/