How to rename files recursively deleting white spaces in file names with shell script


Today, I would like to share a small script (in shell) to rename files recursively but replacing white spaces in the files’ names. For this task I have only used standard commands in order to be sure this script will work on any GNU/Linux or UNIX-like operating system (mv, sed, find,..). Enjoy and personalize this script as you need!


# Finding all files in a directory and its children

find $path_to_images -type f -name *.jpg -follow |
while read -r file;
	directory=$(dirname "$file")

	# Delete all the whitespaces in file name using sed
	new_file_name=$(echo $file_name | sed 's/ /-/g')
	mv "$file" "$new_path";
	echo "Renamed: $new_path"

Most important lines are:

find $path_to_images -type f -name *.jpg -follow

Which obtains all the files with .jpg extension starting from $path_to_images, and these other lines:

new_file_name=$(echo $file_name | sed 's/ /-/g')

Which replace all white spaces for a dash “-“, in the current $file_name  and then by using the mv command the renaming operation is executed.

That’s it!

Be happy with your code!

Leave a Reply

Your email address will not be published. Required fields are marked *