Linux – How to bulk rename files to remove an extraneous space from before the extension

bashfindlinuxrenameshell

I have a bunch of files who's filename follows the pattern 'filename.ext'. eg:

filename .ext

I would like to rename all of these to remove the space before the .ext. eg:

filename.ext

I can find them all using

find * -type f -name'* .*'

but how can I then rename all these files?

Best Answer

Make a file named "renamethis.sh". Its contents should be:

#!/bin/bash
mv "$1" "$(echo $1 | sed 's/ \././')"

Set the executable bit: chmod a+x renamethis.sh. Then, run something like:

find /path/to/dir -name '* .*' -type f -print0 | xargs -0L 1 /path/to/renamethis.sh

YMMV, no warranty express or implied, etc.

FWIW, the spaces are what makes this strange; as long as you don't have other oddball characters in the files names, you're good to go with this approach. If you do, you may want to consider something like a scandir/readdir loop in Perl or PHP, but the above script is the first thing that came to mind.