printf field width doesn't support multibyte characters?

前端 未结 6 489
孤独总比滥情好
孤独总比滥情好 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 05:00

    This is kind of late, but I just came across this, and thought I would post it for others coming across the same post. A variation to @ninjalj's answer might be to create a function that returns a string of a given length rather than calculate the required format length:

    #!/bin/bash
    function sized_string
    {
            STR=$1; WIDTH=$2
            local BYTEWIDTH=$( echo -n "$STR" | wc -c )
            local CHARWIDTH=$( echo -n "$STR" | wc -m )
            FMT_WIDTH=$(( $WIDTH + $BYTEWIDTH - $CHARWIDTH ))
            printf "%*s" $FMT_WIDTH $STR
    }
    printf "[%s]\n" "$(sized_string "abc" 20)"
    printf "[%s]\n" "$(sized_string "ab•cd" 20)"
    

    which outputs:

    [                 abc]
    [               ab•cd]
    

提交回复
热议问题