Pergunta

I want a bash function to count for the String Width that will comsumed when display. because in my cases, String may contain some wide-charactors (e.g. Chinese). So I cannot just use the length of a string.

function getDisplayWidth ()
{
  ???
}

Then "abc" will return 3 and "前后" should return 4 instead of 2.

Foi útil?

Solução

If your implementation of wc has the -L option, that appears to count the right "thing". (Coreutils has it, not sure if any other do.)

Ex:

$ getw() { wc -L <<< "$1"; }
$ getw 前后
4
$ getw 前a后c
6
$ getw abc前后
7
$ getw "行书 / 行書"
11

Outras dicas

Try wc -m. From the os x man page:

The number of characters in each input file is written to the standard output. If the current locale does not support multibyte characters, this is equivalent to the -c option. This will cancel out any prior usage of the -c option.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top