Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a zero to single digit variable

Trying to add a zero before the varaible if it's less than 10 and create said directory. I can't seem to get the zero to add correctly. Keeps resulting in making 02.1.2011, 02.2.2011 etc,etc.

i=0 for i in {01..31} do     if $i > 10         then             mkdir $path/02.0$i.2011         else                 mkdir $path/02.$i.2011     fi done 
like image 617
Colby Avatar asked Feb 24 '11 00:02

Colby


People also ask

How do I add a zero after a digit in Excel?

In the Add Text dialog box, enter zeroes into the Text box, and choose the After last character option in the Position section, and finally click the OK button. Then the specified trailing zeroes are added to the selected number cells immediately.

How do you add leading zeros to a variable?

If the variable in which you want to add leading zeros contains only numeric values, we can simply use Zw. d format. In this case, we made length of the newly transformed variable as 6.

How do I add a zero in front of a single digit in Python?

Use the str. zfill() method to add leading zeros to the string. The method takes the width of the string and pads it with leading zeros.


1 Answers

You can replace the whole lot with:

for day in 0{1..9} {10..31} ; do     mkdir ${path}/02.${day}.2011 done 

while still not having to start up any external processes (other than what may be in the loop body).

That's probably not that important here since mkdir is not one of those things you tend to do a lot of in a tight loop but it will be important if you write a lot of your quick and dirty code in bash.

Process creation is expensive when you're doing it hundreds of thousands of times as some of my scripts have occasionally done :-)

Example so you can see it in action:

pax$ for day in 0{8..9} {10..11}; do echo ${day}; done 08 09 10 11 

And, if you have a recent-enough version of bash, it will honor your request for leading digits:

A sequence expression takes the form {x..y[..incr]}, where x and y are either integers or single characters, and incr, an optional increment, is an integer.

When integers are supplied, the expression expands to each number between x and y, inclusive.

Supplied integers may be prefixed with 0 to force each term to have the same width. When either x or y begins with a zero, the shell attempts to force all generated terms to contain the same number of digits, zero-padding where necessary.

So, on my Debian 6 box, with bash version 4.1.5:

pax$ for day in {08..11} ; do echo ${day} ; done 08 09 10 11 
like image 62
paxdiablo Avatar answered Sep 23 '22 18:09

paxdiablo