Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SPRINTF in shell scripting?

Tags:

bash

shell

printf

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.

like image 762
Manu R Avatar asked Dec 07 '10 14:12

Manu R


People also ask

What does sprintf do in Linux?

Basically sprintf() stands for “String Print”. Unlike standard printf() which write to stdout, sprintf stores output on the character buffer supplied to it.

Can we use printf in shell script?

printf is a shell builtin in Bash and in other popular shells like Zsh and Ksh. There is also a standalone /usr/bin/printf binary, but the shell built-in version takes precedence. We will cover the Bash builtin version of printf . The -v option tells printf not to print the output but to assign it to the variable.

What is printf in bash?

The bash printf command is a tool used for creating formatted output. It is a shell built-in, similar to the printf() function in C/C++, Java, PHP, and other programming languages. The command allows you to print formatted text and variables in standard output.

What library is sprintf in?

The C library function int sprintf(char *str, const char *format, ...) sends formatted output to a string pointed to, by str.


1 Answers

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.

like image 86
Dennis Williamson Avatar answered Sep 19 '22 11:09

Dennis Williamson