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 theperl
package supports regular expressions:Alternatively,
The
-i
flag will makerename
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'srename
.All: First, check to see if Perl's
rename
is available under the nameprename
.Debian: Perl's rename should be the default. It is also available as
prename
. Therename
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 asperl-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:Direct Download:
rename
is also available from Perl Monks: