Remove All Illegal Characters from All Filenames in a Given Folder and subfolders

4

1

I Know this was was basically answered and the automator with the shell script (Sanitize Filenames) works great, but I need it to also do all subfolders as well. And if possible trim the file name down to 50 characters while retaining the file extension. I had found a line of bash code that truncated the file but it also stripped the extension and that does not work well when transferring these files from Macs to Windows.

The script as it stands is this

for f in "$1"/*; do
dir=$(dirname "$f")
file=$(basename "$f")
mv "$f" "${dir}/${file//[[:cntrl:]\\\/:*?\"<>|]/_}" 
done 

I am not opposed to using applescript in automator to complete this task.

Tim Moseley

Posted 2016-03-11T14:08:59.290

Reputation: 41

note: In unix/linux there is an optional command called "rename", and with a quick Google search I find there are many similar command for mac. I think you should check these commands. These "rename" commands use sed expressions (regex + others) to construct the final name. – Giacomo Catenazzi – 2016-03-11T14:21:31.587

is there a way to make this do subfolders? I am also trying to trim the filename to 30 characters while retaining the extension. Any ideas? I have this: mv"$f" "${dir}/${file:0:30} this works great but removes extension which I need since the files are being transferred to a Windows system. – Tim Moseley – 2016-03-14T12:52:54.970

1I would do something like '{0,30}(.[^.])?$' as regex. Using rename or with "find | sed | bash", where in sed I construct the mv command – Giacomo Catenazzi – 2016-03-14T13:21:53.867

Answers

0

You can use find. The options in OSX/Darwin's find are slightly different than those in other *nix variants, so some of these features may not be available for you, but you'll get the gist and can play with the options you do have available:

find -regextype posix-extended -regex '.*\/[^\/]*[[:cntrl:]\\:*?"<>|].*' -print \
  -exec mv "{}" "$(echo "{}" | perl -ane 'chomp; s/[[:cntrl:]\\:*?"<>|]//g; print' -)"

Ziggy Crueltyfree Zeitgeister

Posted 2016-03-11T14:08:59.290

Reputation: 293