printf field width doesn't support multibyte characters?

前端 未结 6 444
孤独总比滥情好
孤独总比滥情好 2021-01-15 04:21

I want printf to recognize multi-byte characters when calculating the field width so that columns line up properly... I can\'t find an answer to this problem and was wonderi

6条回答
  •  有刺的猬
    2021-01-15 04:47

    The best I can think of is:

    function formatwidth
    {
      local STR=$1; shift
      local WIDTH=$1; shift
      local BYTEWIDTH=$( echo -n "$STR" | wc -c )
      local CHARWIDTH=$( echo -n "$STR" | wc -m )
      echo $(( $WIDTH + $BYTEWIDTH - $CHARWIDTH ))
    }
    
    printf "## %5s %*s %5s ##\n## %5s %*s %5s ##\n" \
        '' $( formatwidth "*" 5 ) '*' '' \
        '' $( formatwidth "•" 5 ) "•" ''
    

    You use the * width specifier to take the width as an argument, and calculate the width you need by adding the number of additional bytes in multibyte characters.

    Note that in GNU wc, -c returns bytes, and -m returns (possibly multibyte) characters.

提交回复
热议问题