printf field width doesn't support multibyte characters?

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

    I will probably use GNU awk:

    awk 'BEGIN{ printf "## %5s %5s %5s ##\n## %5s %5s %5s ##\n", "", "*", "", "", "•", "" }'
    ##           *       ##
    ##           •       ##
    

    You can even write shell wrapper function called printf on top of awk to keep same interface:

    tr2awk() { 
        FMT="$1"
        echo -n "gawk 'BEGIN{ printf \"$FMT\""
        shift
        for ARG in "$@"
            do echo -n ", \"$ARG\""
        done
        echo " }'"
    }
    

    and then override printf with simple function:

    printf() { eval `tr2awk "$@"`; }
    

    Test it:

    # buggy printf binary test:
    /usr/bin/printf "## %5s %5s %5s ##\n## %5s %5s %5s ##\n" '' '*' '' '' "•" ''
    ##           *       ##
    ##         •       ##
    # buggy printf shell builin test:
    builtin printf "## %5s %5s %5s ##\n## %5s %5s %5s ##\n" '' '*' '' '' "•" ''
    ##           *       ##
    ##         •       ##
    
    # fixed printf function test:
    printf "## %5s %5s %5s ##\n## %5s %5s %5s ##\n" '' '*' '' '' "•" ''
    ##           *       ##
    ##           •       ##
    

提交回复
热议问题