MacOS – How to remove space character (whitespace) from end of filenames and foldernames

command linemacosspacesterminal

Problem with mac is that it allows space character at end of file or folder.
If this file or folder with space character in end is beeing copied to FTP using Filezilla or Dropbox then mac makes folders with "Foldername_WhiteSpaceConflict"
To get rid of this problem all files and folders with space character needs to be renamed without space character.
What solution could be the best using terminal or some program?

Best Answer

Here's the script to find and remove trailing space from files and dirs:

#!/bin/bash                                                                                                                                                                                                        

IFS=$'\n'
for file in $(find -d . -name "* ")
do
  target_name=$(echo "$file" | sed 's/[ \t]*$//')
  if [ "$file" != "$target_name" ]; then
      if [ -e "$target_name" ]; then
          echo "WARNING: $target_name already exists, file not renamed"
      else
          echo "Move $file to $target_name"
          mv "$file" "$target_name"
      fi
  fi
done