在bash脚本中,如何获取字符串的显示宽度

Nyb*_*ble 5 bash widechar

我想要一个 bash 函数来计算显示时所消耗的字符串宽度。\n因为在我的情况下,字符串可能包含一些宽字符(例如中文)。所以我不能只使用字符串的长度。

\n\n
function getDisplayWidth ()\n{\n  ???\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

那么“abc”将返回 3\n,“\xe5\x89\x8d\xe5\x90\x8e”应该返回 4 而不是 2。

\n

Mat*_*Mat 4

如果您的实现wc有这个-L选项,那么这似乎是正确的“事情”。(Coreutils 有,不确定其他是否有。)

\n\n

前任:

\n\n
$ getw() { wc -L <<< "$1"; }\n$ getw \xe5\x89\x8d\xe5\x90\x8e\n4\n$ getw \xe5\x89\x8da\xe5\x90\x8ec\n6\n$ getw abc\xe5\x89\x8d\xe5\x90\x8e\n7\n$ getw "\xe8\xa1\x8c\xe4\xb9\xa6 / \xe8\xa1\x8c\xe6\x9b\xb8"\n11\n
Run Code Online (Sandbox Code Playgroud)\n