busy-bee.net buzz buzz buzz goes the honeybee home | blog | links | about me

linux to an imac

2002-07-12 10:55 / renaming files  »

I was going to say how easy it is to rename files without a GUI, but Part 3 below took a while for me to figure out because of spaces in filenames and xargs not having the -i switch on my mac ... anyway though:

There seems to be quite a few bits of shareware - or maybe 'spivware' if you go with oblomovka (more blogs akin to this) - that replicates functionality that can be easily done in the shell. So, combined with I think someone on macslash's site who asked "is the shell for anyone except geeks", I thought I'd just show how it can be used it to, e.g., rename files. This is all in zsh by the way (or bash), *not* the default tcsh, which I've never learned.

Part 1:
Rename all files called .html to .shtml:
for i in *.html; do mv $i "`basename $i .html`.shtml"; done

Part 2:
As 1, but with the date in YYYY-MM-DD prepended to the filename:
for i in *.html; do mv $i "`date +%Y-%m-%d``basename $i .html`.shtml "; done

Neither of those recurse though. For that you need find (aside: locate is miles quicker than sherlock for finding files, find is miles more customisable. I haven't even checked that it is ...). So:

Part 3:
As 1, but for all subdirectories as well:

find . -name "*.html" |
while read fname
  do mv "$fname" "`dirname $fname`/`basename $fname .html`.shtml" 
done

The only thing here that you won't find easily with man (man zshmisc for the for,while) is the backticks. Basically, if you surround a command with backticks it and the ticks are substituted with the result of executing the command.

Er .. that'll be $15 please ;-)

mod_perl -- Speed, Power, Scalability