gpt4 book ai didi

bash - 如何将文本与 printf 对齐到具有非 ascii 字符的列中?

转载 作者:行者123 更新时间:2023-12-05 06:12:13 25 4
gpt4 key购买 nike

即使使用非 ascii 字符,我如何使 printf 将值对齐到列中?

以下命令应将第二个和第三个参数中的值对齐到固定的 20 个字符宽度:

printf "%-20s %-20s\n" "Foo" "Bar"
printf "%-20s %-20s\n" "Fooo" "Bar"
printf "%-20s %-20s\n" "Foooó" "Bar"
printf "%-20s %-20s\n" "Foooóó" "Bar"

我希望打印以下内容:

Foo                  Bar
Fooo Bar
Foooó Bar
Foooóó Bar

实际上,这是打印出来的:

Foo                  Bar
Fooo Bar
Foooó Bar
Foooóó Bar

出于某种原因,任何非 ascii 字符(例如我示例中的 ó)都会将列缩短 1 个字符。

最佳答案

非 ascii 字符,例如ó 不像单宽字符的 ASCII 那样打印。

一种解决方案是在 printf 中的两个字符串之间使用 tab 字符并将输出管道输出到 column:

prnt() {
printf "%-20s\t%-20s\n" "Foo" "Bar"
printf "%-20s\t%-20s\n" "Fooo" "Bar"
printf "%-20s\t%-20s\n" "Foooo" "Bar"
printf "%-20s\t%-20s\n" "Fooooo" "Bar"
printf "%-20s\t%-20s\n" "Foooooo" "Bar"
printf "%-20s\t%-20s\n" "Fooooooo" "Bar"
printf "%-20s\t%-20s\n" "Foooooooo" "Bar"
printf "%-20s\t%-20s\n" "Fooooooooo" "Bar"
printf "%-20s\t%-20s\n" "Foooooooooo" "Bar"
printf "%-20s\t%-20s\n" "Fóó" "Bar"
printf "%-20s\t%-20s\n" "Fóóó" "Bar"
printf "%-20s\t%-20s\n" "Fóóóó" "Bar"
printf "%-20s\t%-20s\n" "Fóóóóó" "Bar"
printf "%-20s\t%-20s\n" "Fóóóóóó" "Bar"
printf "%-20s\t%-20s\n" "Fóóóóóóó" "Bar"
printf "%-20s\t%-20s\n" "Fóóóóóóóó" "Bar"
printf "%-20s\t%-20s\n" "Fóóóóóóóóó" "Bar"
printf "%-20s\t%-20s\n" "Fóóóóóóóóóó" "Bar"
}

prnt | column -t -s $'\t'

Online Demo

输出:

Foo                   Bar                 
Fooo Bar
Foooo Bar
Fooooo Bar
Foooooo Bar
Fooooooo Bar
Foooooooo Bar
Fooooooooo Bar
Foooooooooo Bar
Fóó Bar
Fóóó Bar
Fóóóó Bar
Fóóóóó Bar
Fóóóóóó Bar
Fóóóóóóó Bar
Fóóóóóóóó Bar
Fóóóóóóóóó Bar
Fóóóóóóóóóó Bar

关于bash - 如何将文本与 printf 对齐到具有非 ascii 字符的列中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63682751/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com