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=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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)