Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Padding zeros in a string

Tags:

bash

People also ask

How can I pad a string with zeros on the left?

leftPad() method to left pad a string with zeros, by adding leading zeros to string.

How do you add zeros to a string?

The format() method of String class in Java 5 is the first choice. You just need to add "%03d" to add 3 leading zeros in an Integer. Formatting instruction to String starts with "%" and 0 is the character which is used in padding.

How do I add a zero padding in Python?

The zfill() method adds zeros (0) at the beginning of the string, until it reaches the specified length. If the value of the len parameter is less than the length of the string, no filling is done.

How do you add a padding to a string in Java?

Use the String. format() method to pad the string with spaces on left and right, and then replace these spaces with the given character using String. replace() method. For left padding, the syntax to use the String.


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.


Seems you're assigning the return value of 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

Attention though if your input string has a leading zero!
printf will still do the padding, but also convert your string to hex octal format.

# looks ok
$ echo `printf "%05d" 03`
00003

# but not for numbers over 8
$ echo `printf "%05d" 033`
00027

A solution to this seems to be printing a float instead of decimal.
The trick is omitting the decimal places with .0f.

# works with leading zero
$ echo `printf "%05.0f" 033`
00033

# as well as without
$ echo `printf "%05.0f" 33`
00033

to avoid context switching:

a="123"
b="00000${a}"
c="${b: -5}"

n=`printf '%03d' "2"`

Note spacing and backticks


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.