OS X renaming using parameter expansion

Sat, Oct 18, 2014

When it comes to rename files via
command line there is no rename utility under OS X without
installing Homebrew. But I still
never needed to install it since there is a lot you can do by
just making use of the shell parameter
expansion.

The parameter expansion allows you to manipulate
variables in a very convenient way and when mixed with the mv
command you have an unstoppable renaming tool. Let's see first
what are variables and what is this parameter expansion:

$ var='PIC0001.JPG'
$ echo ${var}
PIC0001.JPG

In the example above you can see that we have assigned the value
PIC0001.JPG to a variable named var and in the next line we have
just printed its content. The same example with a little bit of
magic:

$ echo ${var/PIC/2014_Holiday_}
2014_Holiday_0001.JPG

Here I substituted the ugly PIC preffix used by the photo camera
and added the title of the album. We'll see the details on how
this works later on.

Now if I wanted to rename all the pictures from
the command line I would just iterate over all them:

for file in *.JPG; do echo mv "$file" "${file/PIC/2014_Holiday_}"; done

You can safely execute the previous command, no change will be
made to this files because we added the echo to just show the
command to be executed. Delete it to make changes effective.

Now that we have seen a simple example for remaning let's get
deeper on what you can do with parameter
expansion with some examples.

In order to do some safe testing I would recommend creating a new
directory and inside put some random empty files:

for i in $(seq 1 100); do touch "$i-${RANDOM}-$i.txt"; done

That will create something like:

$ ls
1-21912-1.txt 2-16712-2.txt 3-22319-3.txt ...

Now that you have the dummy files test and understand the
following examples:

Replacing patterns with strings

The format of this expansion is:

# Replace first match of the pattern only:
${variable/pattern/replace}
# Replace all matches of the pattern:
${variable//pattern/replace}