SPRINTF in shell scripting? SPRINTF in shell scripting? bash bash

SPRINTF in shell scripting?


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=02var=$(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=2printf -v var 'FILE=_%04d_%06d.dat' "$val1" "$val2"

or with dynamic widths:

val1=8; val2=2width1=4; width2=6printf -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.


Why not using the printf program from coreutils?

$ printf "FILE_%02d_%02d.dat" 1 2FILE_01_02.dat


Try:

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

Example:

$ echo bar | sprintf "foo %s"foo bar