Remove Spaces, Hyphens, and Underscores in Filenames – How to

filesrenameshell-script

What is a good command to delete spaces, hyphens, and underscores from all files in a directory, or selected files?

I use the following command with Thunar Custom Actions to slugify filenames:

for file in %N; do mv "$file" "$(echo "$file" | tr -s ' ' | tr ' A-Z' '-a-z' | tr -s '-' | tr -c '[:alnum:][:cntrl:].' '-')"; done

But that command only replaces spaces with dashes/hyphens and lowercases capped characters.

I've used the following command in terminal to delete spaces from thousands of filenames in a folder, and it worked pretty fast:

 rename "s/ //g" *

Again, it only deletes spaces, and not hyphens/dashes and underscores as well.

Ideally I don't want any spaces, hyphens/dashes, and underscores in my filenames. And it would be great if the command could be used with Thunar Custom Actions on selected files.

Best Answer

The version of rename that comes with the perl package supports regular expressions:

rename "s/[-_ ]//g" *

Alternatively,

rename -i "s/[-_ ]//g" *

The -i flag will make rename use interactive mode, prompting if the target already exists, instead of silently overwriting.

Perl's rename is sometimes called prename.

Perl's rename versus util-linux's rename

On Debian-like systems, perl's rename seems to be the default and the above commands should just work.

On some distributions, the rename utility from util-linux is the default. This utility is completely incompatible with Perl's rename.

  • All: First, check to see if Perl's rename is available under the name prename.

  • Debian: Perl's rename should be the default. It is also available as prename. The rename executable, though, is under the control of /etc/alternatives and thus could have been altered to something different.

  • archlinux: Run pacman -S perl-rename and the command is available as perl-rename. For a more convenient name, create an alias. (Hat tip: ChiseledAbs)

  • Mac OSX According to this answer, rename can be installed on OSX using homebrew via:

    brew install rename 
    
  • Direct Download: rename is also available from Perl Monks:

     wget 'http://www.perlmonks.org/?displaytype=displaycode;node_id=303814' -O rename
    
Related Question