2016-04-03 58 views
1

How to justify and center text in bash?显示如何在bash中居中文本。它仅适用于每个字符占用一列(如英文字母)的情况。有许多人物至少占据两列,如“你好”。如何获取终端中某个角色占用的列数?

如何获取终端中指定字符占用的列数?

+0

你有一个字符占用多列的例子吗? –

+0

@BenjaminW。 “你好” – letiantian

+0

https://github.com/urwid/urwid/blob/master/urwid/old_str_util.py中的'get_width'函数可以解决这个问题。 – letiantian

回答

2

一个简单的选项是GNU wc。从手册页:

-L--max-line-length
打印的最大显示宽度

所以在您的评论的例子:

$ wc -L <<< '你好' 
4 

这可以做成一个小功能:

getwidth() { 
    for str; do 
     echo "$str: $(wc -L <<< "$str")" 
    done 
} 

这可以用来如下:

$ getwidth 你 好 a 
你: 2 
好: 2 
a: 1 

This Unix & Linux Q&A有一些很好的指针。

1

https://github.com/urwid/urwid/blob/master/urwid/old_str_util.py给出了一个备选答案,其中get width可以通过其unicode序号获得一个字符的宽度。

widths = [ 
    (126, 1), 
    (159, 0), 
    (687, 1), 
    (710, 0), 
    (711, 1), 
    (727, 0), 
    (733, 1), 
    (879, 0), 
    (1154, 1), 
    (1161, 0), 
    (4347, 1), 
    (4447, 2), 
    (7467, 1), 
    (7521, 0), 
    (8369, 1), 
    (8426, 0), 
    (9000, 1), 
    (9002, 2), 
    (11021, 1), 
    (12350, 2), 
    (12351, 1), 
    (12438, 2), 
    (12442, 0), 
    (19893, 2), 
    (19967, 1), 
    (55203, 2), 
    (63743, 1), 
    (64106, 2), 
    (65039, 1), 
    (65059, 0), 
    (65131, 2), 
    (65279, 1), 
    (65376, 2), 
    (65500, 1), 
    (65510, 2), 
    (120831, 1), 
    (262141, 2), 
    (1114109, 1), 
] 

# ACCESSOR FUNCTIONS 

def get_width(o): 
    """Return the screen column width for unicode ordinal o.""" 
    global widths 
    if o == 0xe or o == 0xf: 
     return 0 
    for num, wid in widths: 
     if o <= num: 
      return wid 
    return 1 

https://github.com/someus/terminal-text-width给出了节点的相应实现。

相关问题