I tell my NSS students often that software developers, at their core, are really lazy. In fact, we'll spend immeasureable hours coding a solution that will allow us to avoid a manual task that the solution replaces.

Case in point - for my front end curriculum, I number the directories in my git repo.


Unfortunately, this causes an issue when I want to inject a new module at, oh say, 21. When there are 44 modules, that means I would have to manually rename all modules from 21-44 in order to make my new one fit in the naming convention. Well, since I'm lazy and don't want to do that, I spent a few hours tonight playing around writing a bash script that will automate that process for me.

Yes, I could have manually renamed all those directories in a manner of minutes, but what if I needed to do it again in 10 minutes, and then again tomorrow, etc?

Here you go. My amateur bash solution.



for directory in `ls -d */`  
  dir=$(basename "$directory")
  pattern=([0-9][0-9])-[0-9a-zA-z-]+  # The RegEx pattern to match
  if [[ $dir =~ $pattern ]] ; then  # See if it matches
    currentModuleNumber="10#${BASH_REMATCH[1]}"; # Get the module number (base 10)
    if [[ $currentModuleNumber -ge $STARTDIR ]] ; then # Only start renumbering 
                                                       # when the module number is >= 
                                                       # the parameter value
      newPrefix="00$(($currentModuleNumber + 1))" # Increase the module number
      trimmed=${newPrefix:(-2)}; # Pad any numbers less than 10 with a 0
      mv $dir "$trimmed$(echo $dir | sed -e 's/^..//')"; # Rename the directory
    echo "${BASH_REMATCH[0]} did not match";

Blog Logo

Steve Brownlee

Head Coach at Nashville Software School. Evolving software development education.