Life's lessons expressed in UTF-8

Renaming Multiple Files With a Common Prefix

Last week, while putting together a quick slide show presentation, I found myself having to rename a set of images sharing a common prefix. The images had filenames that started with the prefix cidemot, which I needed to change to cidemo_current.
Since I work mostly on Mac Os X Snow Leopard, live in the terminal, and love me some regular expressions, I wrote a quick one line shell command to rename all of the files for me. Please note that while the following command solved my problem it can lead to the lost of data if not used correctly. So I advise that use it with caution and, if possible, test it on a sample set of files and/or environment.
Multi-File rename command
ls cidemot_* | xargs -n1 -I {} echo {} | sed 's/^cidemot\(.*\)/cp cidemot\1 cidemo_current\1/g' | sh

rm -rf cidemot_*
After renaming the files to the new expected format I deleted the original files with the rm (remove) command. I could have easily used the mv (move) command in the above script to rename and delete the original files in 1 swift move. But I always like to go with a 2 phase rename process so that I can verify the new files before deleting the originals (essentially making a backup).

Command Breakdown, How does it work?

First we start off by listing all of the files with the original prefix and piping the result to the xargs command one line at a time -n1. The -I {} is used for string substitution needed for echoing the filenames as they are to the sed command.

ls cidemot_* | xargs -n1 -I {} echo {}
The xargs command output is then piped, 1 at a time, to sed where we use regular expressions for doing a search and replace on the filename strings. In this particular snippet of code sed is being used to create a copy command string from the original filename, which can then be piped to the sh (shell command) for copying the original file to a new file with the expected filename (e.g. cp cidemot_patch_image.png cidemo_current_patch_img.png).
sed 's/^cidemot\(.*\)/cp cidemot\1 cidemo_current\1/g' | sh