#!/bin/csh -f # rename # ------------------------------------------------------------------------- # C shell script to mimic the Linux rename command, which does not exist on # Mac OS X, renaming multiple files. # ------------------------------------------------------------------------- # Revision History: # $Log$ # ------------------------------------------------------------------------- # Collect command line options set option_quiet = "false" set option_prefix_string = "" while ($#argv > 0) if ("$1" == "-h" || "$1" == "--help") then echo "Changes all occurrences of 'from' to 'to' in names of files." echo "Usage: $0:t [options] from to files..." echo "Options:" echo " -h = Show this help text" echo " --help = Show this help text" echo " -q = Quiet (no prompt for overwriting files)" echo " -p prefix_string = Prefix each output line with prefix_string" echo " (Only valid with -q)" echo "Examples:" echo " $0:t .jpeg .jpg *.jpeg" echo " $0:t -q .JPG .jpg *.JPG" echo " $0:t -q ' ' '_' *" echo " $0:t -q a A *" echo " $0:t -q -p 'Renamed: ' old new *" exit 1 else if ("$1" == "-q") then shift set option_quiet = "true" else if ("$1" == "-p") then shift set option_prefix_string = "$1" shift else if ("-" == "`echo $1:q | cut -c 1`") then echo "Error: Invalid option: $1:q" $0 --help exit 1 else # Not a recognized option. Assume it's the first argument break endif end # Can't have option_prefix_string without option_quiet. Allowing the mv # command to prompt would mess up the prefixing. if ("$option_prefix_string" != "" && "$option_quiet" == "false") then echo "Error: Can't use -p without -q." $0 -h exit 1 endif # At least 3 arguments required if ($#argv < 3) then echo "Error: At least 3 arguments required." $0 -h exit 1 endif set from = $1:q shift set to = $1:q shift foreach file ($*:q) # Note: Don't mess with the single/double quotes # Need double quotes to trigger variable substition in mv, but # need single quotes inside the double quotes to avoid nesting # problems in echo. set to_file = `echo "$file:q" | sed -e "s/$from/$to/g"` # Skip files that didn't have the from pattern in them at all. Don't # want mv -i to prompt the user for all those extra files. And don't # want mv -v to echo the names of all those extra files. if ("$file:q" != "$to_file:q") then set option_interactive_string = "-i" if ("$option_quiet" == "true") then set option_interactive_string = "" endif if ("$option_prefix_string" == "") then echo "mv -v $option_interactive_string '$file:q' '$to_file:q'" else echo -n "$option_prefix_string" endif mv -v $option_interactive_string "$file:q" "$to_file:q" endif end