SPRINTF in shell scripting?

后端 未结 3 1268
时光取名叫无心
时光取名叫无心 2020-12-24 05:26

I have an auto-generated file each day that gets called by a shell script. But, the problem I\'m facing is that the auto-generated file has a form of:

FIL         


        
相关标签:
3条回答
  • 2020-12-24 05:53

    Try:

    sprintf() { local stdin; read -d '' -u 0 stdin; printf "$@" "$stdin"; }
    

    Example:

    $ echo bar | sprintf "foo %s"
    foo bar
    
    0 讨论(0)
  • 2020-12-24 06:03

    Why not using the printf program from coreutils?

    $ printf "FILE_%02d_%02d.dat" 1 2
    FILE_01_02.dat
    
    0 讨论(0)
  • 2020-12-24 06:07

    In Bash:

    var=$(printf 'FILE=_%s_%s.dat' "$val1" "$val2")
    

    or, the equivalent, and closer to sprintf:

    printf -v var 'FILE=_%s_%s.dat' "$val1" "$val2"
    

    If your variables contain decimal values with leading zeros, you can remove the leading zeros:

    val1=008; val2=02
    var=$(printf 'FILE=_%d_%d.dat' $((10#$val1)) $((10#$val2)))
    

    or

    printf -v var 'FILE=_%d_%d.dat' $((10#$val1)) $((10#$val2))
    

    The $((10#$val1)) coerces the value into base 10 so the %d in the format specification doesn't think that "08" is an invalid octal value.

    If you're using date (at least for GNU date), you can omit the leading zeros like this:

    date '+FILE_%-m_%-d.dat'
    

    For completeness, if you want to add leading zeros, padded to a certain width:

    val1=8; val2=2
    printf -v var 'FILE=_%04d_%06d.dat' "$val1" "$val2"
    

    or with dynamic widths:

    val1=8; val2=2
    width1=4; width2=6
    printf -v var 'FILE=_%0*d_%0*d.dat' "$width1" "$val1" "$width2" "$val2"
    

    Adding leading zeros is useful for creating values that sort easily and align neatly in columns.

    0 讨论(0)
提交回复
热议问题