15 May 2013

Naming Names, Part 1

I frequently go off on tangents. While watching some youtube videos I'd downloaded, I got the notion that it'd be neater to see them all grouped into the teams they are on. I was about to use my trusty, crusty, old bash function to rename them when it occurred to me that it was past due for an update. For reference, here is the function I've been using in my profile since Forever:-
function filenamesed () {
   if [ "$1" = "" -o "$2" = "" ]; then
      echo "Usage: filenamesed 'sedcmds' filename(s)"
      return
   fi
   SEDCMD="$1"
   shift
   while [ "$1" != "" ]; do
      F="$1"
      NF=`echo "$F" | sed "$SEDCMD"`
      if [ "$F" != "$NF" ]; then
         echo "$F -> $NF"
         mv -i "$F" "$NF"
      fi
      shift
   done
}
I won't explain it in depth. Suffice to say that it takes a GNU sed command as its first argument, and a bunch of files as other arguments, and then applies that sed command to the filenames. For example, when I want to change all the underscores in filenames into spaces, I would run:-
filenamesed 's/_/ /g;' videos/youtube/*.mp4
So if the original goal was "Watch some MindCrack UHC" and Tangent #1 was "rename those files", Tangent #2 is "update your crusty old shell script" and we finally come to the maximally-tangental task of bringing you lovely people along for the ride. Let's do this in Perl 5, piecemeal, and explain our thought processes along the way.