Web Hosting Talk







View Full Version : Linux Shell Renaming Script Needed


Joshua
08-16-2005, 09:27 AM
I'm transferring data from Macs to PCs right now, and currently have to manually rename every file that has an illegal character for Windows in it (such as / and &). Does anyone know how to make a shell script that will go through all directories and replace the "/" in file names with a "-", and replace a "&" with a "+"? Also, is there a way to add a single file extension to every file in a single directory? I'd be doing this through the Mac OS X BSD (darwin) backend.

Thanks!

knightfoo
08-16-2005, 11:20 AM
If you have perl installed then you should have the perl "rename" command as well. You could add an extension to all files in a directory like this:

rename 's/$/.ext/' *

If you add -n after rename it will show you what it will do before it does it, just to make sure it is right. Recursive renaming is a little more difficult ..

#/bin/bash
for dir in `find /basedir -type d` ; do
cd $dir && rename -n 'y/\/\&/-+/' * # Remove the -n when you really want to do it
done

Or if you don't have perl:

#/bin/bash
for i in `find /basedir -type f` ; do
dir=`dirname $i`
file=`basename $i`
newfile=`echo $file | tr -- \/\& -+ # The double dash after tr is necessary
echo "Moving $dir/$file to $dir/$newfile"
# mv $dir/$file $dir/$newfile # Uncomment after you test that the renaming worked
done

I don't have an OSX or BSD box handy to test this, but it should work. The only differences might be shell escaping. You should of course make a backup copy of the directories before running these scripts, just in case. :)