I'm decommissioning a Mac OS X server which hosts a stack of files and directories with file names that contain illegal chacters. I need to sort the file names out before I can move the files.
I'm after a bash script that will traverse all the subdirectories within a given directory, and for each directory and file contained within, remove any space characters at the beginning or end of the directory/file name and replace any illegal characters with an alternative character, say an underscore or hyphen?
I think the code below is the beginning of what I'm after but...
- it doesn't deal with files names that have leading/trailing spaces
- it doesn't handle directories
- it only works on the files in one folder
- it only matches one illegal character ("/" in this eg.) (I'm not familiar with useage of sed to know if it can be used to match & replace multiple alternative chars)
- don't know if trying to match "/" will work because won't "ls /" list the root directory? Can I use "\/"?
Code:
#!/bin/bash
illegal=/
replace=_
for i in $( ls *$illegal* );
do
src=$i
tgt=$(echo $i | sed -e "s/$illegal/$replace/")
mv $src $tgt
done