【问题标题】:Setw and setfill equivalent in BASHBASH 中的 setw 和 setfill 等价物
【发布时间】:2010-08-12 01:37:45
【问题描述】:

您能否告诉我以下 C++ sn-p 的等效 BASH 代码是什么:

std::cout << std::setfill('x') << std::setw(7) << 250;

输出是:

xxxx250

感谢您的帮助!

【问题讨论】:

    标签: bash setw


    【解决方案1】:

    如果您使用的是 Linux,它有一个 printf 程序用于此目的。其他 UNIX 变体也可能有它。

    使用x 填充数字并不是真正的用例,但您可以通过以下方式获得相同的结果:

    pax> printf "%7d\n" 250 | tr ' ' 'x'
    xxxx250
    

    输出带有空格填充的 250,然后使用 tr translate 实用程序将这些空格转换为 x 字符。

    如果您正在寻找仅限bash 的解决方案,您可以从:

    pax> n=250 ; echo ${n}
    250
    
    pax> n=xxxxxxx${n} ; echo ${n}
    xxxxxxx250
    
    pax> n=${n: -7} ; echo ${n}
    xxxx250
    

    如果你想要一个通用的解决方案,你可以使用这个函数fmt,包含单元测试代码:

    #!/bin/bash
    #
    # fmt <string> <direction> <fillchar> <size>
    # Formats a string by padding it to a specific size.
    # <string> is the string you want formatted.
    # <direction> is where you want the padding (l/L is left,
    #    r/R and everything else is right).
    # <fillchar> is the character or string to fill with.
    # <size> is the desired size.
    #
    fmt()
    {
        string="$1"
        direction=$2
        fillchar="$3"
        size=$4
        if [[ "${direction}" == "l" || "${direction}" == "L" ]] ; then
            while [[ ${#string} -lt ${size} ]] ; do
                string="${fillchar}${string}"
            done
            string="${string: -${size}}"
        else
            while [[ ${#string} -lt ${size} ]] ; do
                string="${string}${fillchar}"
            done
            string="${string:0:${size}}"
        fi
        echo "${string}"
    }
    

     

    # Unit test code.
    
    echo "[$(fmt 'Hello there' r ' ' 20)]"
    echo "[$(fmt 'Hello there' r ' ' 5)]"
    echo "[$(fmt 'Hello there' l ' ' 20)]"
    echo "[$(fmt 'Hello there' l ' ' 5)]"
    echo "[$(fmt 'Hello there' r '_' 20)]"
    echo "[$(fmt 'Hello there' r ' .' 20)]"
    echo "[$(fmt 250 l 'x' 7)]"
    

    这个输出:

    [Hello there         ]
    [Hello]
    [         Hello there]
    [there]
    [Hello there_________]
    [Hello there . . . . ]
    [xxxx250]
    

    您不仅限于打印它们,您还可以使用以下行保存变量以供以后使用:

    formattedString="$(fmt 'Hello there' r ' ' 20)"
    

    【讨论】:

      【解决方案2】:

      您可以像这样打印填充:

      printf "x%.0s" {1..4}; printf "%d\n" 250
      

      如果你想概括这一点,很遗憾你必须使用eval:

      value=250
      padchar="x"
      padcount=$((7 - ${#value}))
      pad=$(eval echo {1..$padcount})
      printf "$padchar%.0s" $pad; printf "%d\n" $value
      

      您可以在 ksh 中直接在大括号序列表达式中使用变量,但不能在 Bash 中使用。

      【讨论】:

        【解决方案3】:
        s=$(for i in 1 2 3 4; do printf "x"; done;printf "250")
        echo $s
        

        【讨论】:

          猜你喜欢
          • 2012-08-27
          • 1970-01-01
          • 2013-07-10
          • 1970-01-01
          • 2017-07-20
          • 2011-09-16
          • 1970-01-01
          • 1970-01-01
          • 2011-09-08
          相关资源
          最近更新 更多