SPRINTF in shell scripting?

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:

FILE_MM_DD.dat

... where MM and DD are 2-digit month and day-of-the-month strings.

I did some research and banged it at on my own, but I don't know how to create these custom strings using only shell scripting.

To be clear, I am aware of the DATE function in Bash, but what I'm looking for is the equivalent of the SPRINTF function in C.


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.


Why not using the printf program from coreutils?

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

Try:

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

Example:

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