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

Hi!

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!

Console-128

# Finding all files in a directory and its children
path_to_images="/Users/alex/Downloads/images"

find $path_to_images -type f -name *.jpg -follow |
while read -r file;
do
	file_name="${file##*/}"
	directory=$(dirname "$file")

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

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')
new_path=$directory'/'$new_file_name

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!

Añade un Comentario

Leave a Reply

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