How long are you prepared to spend trying to find a quick way of doing something?

In my case, well over an hour.

I had about 20 or so .htm files I needed renaming as .php and I couldn’t be bothered to change them all by hand. I have a computer, right? I know a bit of DOS, a bit of UNIX, there must be a nifty command line trick for this, right?

Well, easy enough in DOS:
ren *.htm *.php
would probably do the trick if memory serves.

What about in Mac OS X? There are shareware and freeware programs to do this, but the ones that seemed any good were crippled and I wasn’t prepared to pay $20 for this task. Some didn’t work when downloaded. So back to the command line.

‘mv’ is the rather quaint UNIXy way of renaming files, but
mv *.htm *.php
doesn’t do what you might hope.

So I hit Google. Found something fairly promising, couldn’t figure out why it didn’t work, then I read it more carefully and realised it was the C shell, and OS X uses the BASH shell by default.

Eventually after a lot of swearing at Google, I found this page which had the answer. Copied the code into TextWrangler, saved it as ‘ren’ in the file I was working on and typed
. ren ‘htm$’ ‘php’ *.htm

What a palarver… it would, of course, been far quicker to rename them all by hand. But I couldn’t bear to do that.

—-

#!/bin/sh
# we have less than 3 arguments. Print the help text:
if [ $# -lt 3 ] ; then
cat <<HELP
ren — renames a number of files using sed regular expressions

USAGE: ren ‘regexp’ ‘replacement’ files…

EXAMPLE: rename all *.HTM files in *.html:
ren ‘HTM$’ ‘html’ *.HTM

HELP
exit 0
fi
OLD=”$1″
NEW=”$2″
# The shift command removes one argument from the list of
# command line arguments.
shift
shift
# $* contains now all the files:
for file in $*; do
if [ -f "$file" ] ; then
newfile=`echo “$file” | sed “s/${OLD}/${NEW}/g”`
if [ -f "$newfile" ]; then
echo “ERROR: $newfile exists already”
else
echo “renaming $file to $newfile …”
mv “$file” “$newfile”
fi
fi
done

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply