Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove spaces from filenames in folder

I have a situation where I need to daily go over 400+ files in a folder on Xsan and replace spaces with under-scores in the filenames of the files.

Does anyone one have a script at hand that I can run via the terminal for example that will do this for me?

like image 840
Ronny vdb Avatar asked May 08 '13 15:05

Ronny vdb


People also ask

Should I avoid spaces in folder names?

Don't start or end your filename with a space, period, hyphen, or underline. Keep your filenames to a reasonable length and be sure they are under 31 characters. Most operating systems are case sensitive; always use lowercase. Avoid using spaces and underscores; use a hyphen instead.

Do spaces in file names cause problems?

Avoid spacesA space in a filename can cause errors when loading a file or when transferring files between computers.

Should you use spaces in folder names?

So, while spaces are certainly allowed in the name, you have to be careful there is no space before or after the name. Both hyphen and underscore are also allowed. While spaces aren't likely to cause any issues, as others have pointed out, it is easier to type hypens or underscore in a Terminal command.


1 Answers

Here you go, this loops through all files (and folders) in the current directory:

for oldname in *
do
  newname=`echo $oldname | sed -e 's/ /_/g'`
  mv "$oldname" "$newname"
done

Please do note that this will overwrite files with the same name. That is, if there are two files that have otherwise identical filenames, but one has underscore(s) where the other has space(s). In that situation, the one that had underscores will be overwritten with the one that had spaces. This longer version will skip those cases instead:

for oldname in *
do
  newname=`echo $oldname | sed -e 's/ /_/g'`
  if [ "$newname" = "$oldname" ]
  then
    continue
  fi
  if [ -e "$newname" ]
  then
    echo Skipping "$oldname", because "$newname" exists
  else
    mv "$oldname" "$newname"
  fi
done
like image 113
Ilari Scheinin Avatar answered Sep 17 '22 15:09

Ilari Scheinin