Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Print output with variable leading zeros

Status
Not open for further replies.

ranjit

Technical User
Apr 14, 2000
131
GB
[tt]
I have a requirement to increment a number prefixed with variable leading zeros and print the output.

Input:
0012
000005
000099
0000100

Desired output:
0013
000006
000100
0000101

I'm fine if the output is required to be say 5 digits in length i.e using printf "%05\n" - the variable length per line is creating issues.

Thanks


[/tt]
 
You can use variables in the printf as in:

length=6
printf "%0${length}d\n" 123

which produces:

000123

OR in Korn Shell you can typeset your variables as in:

typeset -Z4 my_var1=56
typeset -Z6 my_var2=432

echo "${my_var1} ${my_var2}"

produces:

0056 000432


I hope that helps.

Mike
 
[tt]
Mike,

Are you sure variable assignment within printf works?

$ cat test.awk
nawk 'BEGIN {

LENGTH=6
printf("%0${LENGTH}d\n", "123")
printf("%08d\n", "123")
}'

$ ./test.awk
{LENGTH}d
00000123

I didn't get the result you suggested.

Thanks
[/tt]
 
printf("%0"LENGTH"d\n", "123")

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
The printf example is a shell example (man printf(1)), and does not work in n/g/awk.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top