In a bash script, how to get the display width of a string

I need a bash function to count the line width that will be displayed when displayed. because in my cases the string may contain some widescreen (for example, Chinese). So I can’t just use the length of the string.

function getDisplayWidth () { ??? } 

Then "abc" will return 3 and "ε‰εŽ" should return 4 instead of 2.

+4
source share
2 answers

If your wc implementation has the -L option, that means counting the correct β€œthing”. (Coreutils has this, not sure what others are doing.)

Example:

 $ getw() { wc -L <<< "$1"; } $ getw ε‰εŽ4 $ getw 前a后c 6 $ getw abcε‰εŽ7 $ getw "葌书 / θ‘Œζ›Έ" 11 
+4
source

Try wc -m . On the os x help page:

The number of characters in each input file is written to standard output. If the current language does not support multibyte characters, this is equivalent to the -c option. This will invalidate any previous use of the -c option.

0
source

Source: https://habr.com/ru/post/1403404/


All Articles