tags:

views:

815

answers:

4

I'm writing a bash script to get some podcasts. The problem is that some of the podcast numbers are one digits while others are two/three digits, therefore I need to pad them to make them all 3 digits.

I tried the following:

n=1

n = printf %03d $n

wget http://aolradio.podcast.aol.com/sn/SN-$n.mp3

but the variable 'n' doesn't stay padded permanently. How can I make it permanent?

+2  A: 

Use backticks to assign the result of the printf command (``):

n=1
wget http://aolradio.podcast.aol.com/sn/SN-`printf %03d $n`.mp3

EDIT: Note that i removed one line which was not really necessary. If you want to assign the output of 'printf %...' to n, you could use

n=`printf %03d $n`

and after that, use the $n variable substitution you used before.

ChristopheD
A: 
n=`printf '%03d' "2"`

Note spacing and backticks

anon
+2  A: 

Seems you're assigning the return value if the printf command (which is its exit code), you want to assign the output of printf.

bash-3.2$ n=1
bash-3.2$ n=$(printf %03d $n)
bash-3.2$ echo $n
001
nos
+1 for using $() - it's much more preferable to backticks
Dennis Williamson
A: 

G'day,

As mentioned by noselad, please command substitution, i.e. $(...), is preferable as it supercedes backtics, i.e. ....

Much easier to work with when trying to nest several command substitutions instead of escaping, i.e. "backslashing", backtics.

HTH

cheers,

Rob Wells