Gentoo Forums
Gentoo Forums
Gentoo Forums
Quick Search: in
Bash, arithmetic expansion and formatting.
View unanswered posts
View posts from last 24 hours

 
Reply to topic    Gentoo Forums Forum Index Portage & Programming
View previous topic :: View next topic  
Author Message
zandor
n00b
n00b


Joined: 19 Apr 2002
Posts: 7

PostPosted: Tue Apr 23, 2002 1:54 pm    Post subject: Bash, arithmetic expansion and formatting. Reply with quote

Starting here with aritmaetic expansion I found a problem where I would like to keep leading zeros.

For example I have,

COUNT=$((1))

for ((X=0; X<20; X++))
do
echo Help$((COUNT))
((COUNT++))
done


Will print out:

Help1
Help2

...
Help18
Help19


Is there an easy way to have leading zeros in the variable expansion so the output is something like:

Help0001
...
Help0018
Help0019


I've tried assigning COUNT as a string first, COUNT=0001, but the end result is only the first iteration has the correct amount of digits.

-Zandor
Back to top
View user's profile Send private message
zandor
n00b
n00b


Joined: 19 Apr 2002
Posts: 7

PostPosted: Tue Apr 23, 2002 2:55 pm    Post subject: printf Reply with quote

I spoke to soon but I found a solution which is printf. In case anyone else is wondering here's how it works.

printf "%d" 4 will simply print a decimal
4

printf "%4d" 4 will print the same but will align the right side of the number to position 4
---4 (replace the dashes with spaces)
and

printf "%04d" 4 tells printf to fill in the left of the number with leading zeros.
0004

I know it's not much of an explanation but printf is a complex function as it follows the C language formatting arguments.

do a man printf for the bash printf and a man 3 printf for the C manpage.

-Zandor
Back to top
View user's profile Send private message
Display posts from previous:   
Reply to topic    Gentoo Forums Forum Index Portage & Programming All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum