Wednesday, January 23, 2013

How To: Recursively Create Numeric Directories

I was asked by a colleague how to do the following:

I have a root folder that I need to create a directory based on job numbers.

From the root folder, I'd like to create the following:

1000
1000\1100
1000\1100\1101
1000\1100\1102

all the way up to 

9000\9900\9999

To explain, I'll use the 5000 folder:

I would need:
5000
5000\5100
5000\5100\5101 through 5000\5100\5199
5000\5200
5000\5200\5201 through 5200\5200\5299
and so on.

What would be the easiest way?

The solution isn't a big deal for anyone familiar with scripting, but I figured I'd share here in case other none coders need help with a similar problem.

I wasn't sure whether they were on a Windows computer (figured most likely based on the slashes) or Linux / Mac, so I provided both a Bash and Windows command shell solutions.

There are any number of ways to approach this, I chose nested for loops.

First the Bash solution:

for x in {1..9}; do
  mkdir ${x}000
  cd ${x}000
  for y in {1..9}; do
    mkdir ${x}${y}00
    cd ${x}${y}00
    for ((z=1; z<=99; z+=1)); do
      mkdir `printf "%s%s%02d" $x $y $z`
    done
    cd ..
  done
  cd ..
done

Now the Windows solution:

setlocal EnableDelayedExpansion
for /l %x in (1, 1, 9) do (
  mkdir %x000
  cd %x000
  for /l %y in (1, 1, 9) do (
    mkdir %x%y00
    cd %x%y00
    for /l %z in (1, 1, 99) do (
      if %z LSS 10 (
        mkdir %x%y0%z
      ) else (
        mkdir %x%y%z
      )
    )
    cd ..
  )
  cd ..  
)

1 comment:

Unknown said...

I think I forgot to mention in the original post, but the examples are designed to copy and paste directly into the command shell window.

To run the Windows example from within a script, I believe you have to add additional % in front of the variables.