Linux – rename files to change spaces to underscore

fileslinuxrename

I have a load of files(mp3, wav, txt, doc) that have been created in MS Windows and they have spaces in their names. eg The file of whoever.doc

I would like to rename them all at once, replacing the space with an underscore or dot.

Best Answer

The shell can do this pretty easily (here assuming ksh93, zsh, bash, mksh, yash or (some builds of) busybox sh for the ${var//pattern/replacement} operator):

for file in *.doc *.mp3 *.wav *.txt
do
  mv -- "$file" "${file// /_}"
done

Change the *.doc ... glob to match whatever files you're interested in renaming.

To rename all of the files in the current directory that currently have spaces in their filenames:

for file in *' '*
do
  mv -- "$file" "${file// /_}"
done

You might also consider adding a "clobber" check:

for file in *' '*
do
  if [ -e "${file// /_}" ]
  then
    printf >&2 '%s\n' "Warning, skipping $file as the renamed version already exists"
    continue
  fi

  mv -- "$file" "${file// /_}"
done

Or use mv's -i option to prompt the user before overriding a file.