Wednesday, July 11, 2012

Rename files with spaces and other unwanted chars (like from MAC)

Some times, I get files from MAC users and... they use all that what the system bring them:
spaces, accents (é ç à è ê ...), and others (&, ° ...)

It is a not easy and time consuming to remove them by hand.
So I made a script. But dealing with spaces was a BIG deal. So I post it.

NOTE: I put my scripts in the $HOME/bin directory so they can be called from everywhere.
  • macos2linux_files.sh scans the current directory for file names to convert and do the job.
  • names_to_char7_echo_mv.sh is creating a mv command when the file name need to be renamed and and do the real hard job :"dealing with spaces"
  • names_to_char7.sh is called to convert the name


macos2linux_files.sh
#!/bin/bash
#remove ._ files
find . -name "._*" -delete

#remove DS_Store files
find . -name "*DS_Store" -delete

#convert spaces
find . -depth -name "* *" -exec echo echo mv \"\\\"{}\\\"\" \`names_to_char7.sh  \"{}\"\` \; > /tmp/todo.sh

source /tmp/todo.sh > /tmp/todo2.sh
source /tmp/todo2.sh

#rename files to usable names
find . -depth -exec echo 'names_to_char7_echo_mv.sh  "{}"'  \; > /tmp/name2char7.sh
cp /tmp/name2char7.sh /tmp/name2char7_reverseorder.sh
sed -n '$!p' /tmp/name2char7_reverseorder.sh >  /tmp/name2char7_reverseorder_moins1.sh 
source /tmp/name2char7_reverseorder_moins1.sh > /tmp/todo.sh 
source /tmp/todo.sh 

names_to_char7_echo_mv.sh
#!/bin/bash
from_name=$(basename "\"$1\"")
dir_name=$(dirname "\"$1\"")
toto_name=`names_to_char7.sh "$from_name" | sed 's/\.\///g'`

if [ "\"$from_name\"" == $toto_name ]; then true; else echo "mv \"`echo "$dir_name"|tr -d '"'`/`echo "$from_name"|tr -d '"'`\"   \"`echo "$dir_name"|tr -d '"'`/`echo "$toto_name"|tr -d '"'`\""; fi

names_to_char7.sh
#!/bin/bash
from_name=$(basename "$1")
to_name=`echo $from_name | tr ' ' '_' | tr "'" '_' | tr -d '[{}(),\!°]' | tr -d "\'" | sed 's/[éèê]/e/g' | sed 's/[ÈÉÊ]/E/g' | sed 's/___/_/g' | sed 's/__/_/g' | sed 's/_-/_/g' | sed 's/-_/_/g' | sed 's/_-_/_/g' | sed 's/__/_/g'`
toto_name=\"$(dirname "$1")/$to_name\"

echo $toto_name