bash - 填充的 printf 格式字符串没有使用多字节字符添加足够的填充

标签 bash shell printf

我经常在 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/

相关文章:

c - 将文件中的信息写入存档文件?

regex - 检查目录是否存在递归地反转路径

bash - 在特定位置插入字符串(定长文件)

c - 如何控制 double 变量小数点字符后出现的位数?

c - C 中连续两次 printf() 调用的奇怪行为

linux - 以 qsub 开头的 shell 脚本的参数

regex - 在 bash 中,如何检查数组中字符串的部分内容?

bash - 将参数传递给存储在 HDFS 中的 shell 脚本

shell - 使用 shell 脚本将值存储在数组中

linux - bash 中是否有命令获取前 n 个单词而不是类似于 'head -n' 的 n 行?