How to rename files recursively with shell script on GNU/Linux and UNIX-like operating systems

Imagine next situation:

You  have too many files without extension but you know they are valid HTML files, so you have to add an “.html” extension to all these files.

Now, if you need to rename thousands of files you will need to do it with a script, definitely.

In order to make this happen, you have to choose in which language the program would work better…, if you have a GNU/Linux or a UNIX-like operating system, then you have one of the most powerful tools to manage files and directories: the shell.

When we create a script that runs in the command line, we say: “the script is a shell script“.

Console-128

Today, I would like to share a short shell script that allows you rename files recursively starting in a base directory:

# Author: Alex Arriaga (@alex_arriaga_m)
# A small shell script for adding an "html" extension to files that don't contain a extension
# For example: "index" will be renamed to "index.html"
# Function: contains(string, substring)
#
# Returns 0 if the specified string contains the specified substring,
# otherwise returns 1.
contains() {
    string="$1"
    substring="$2"
    if test "${string#*$substring}" != "$string"
    then
        return 0    # $substring is in $string
    else
        return 1    # $substring is not in $string
    fi
}

# Finding all files in a directory
root_path_to_content="/home/my-root-directory-for-renaming"

find $root_path_to_content -type f -follow |
while read -r file;
do
	extension=`echo ${file##*.}`
	file_name=`echo ${file%.*}`
	num_chars_ext=`echo ${#extension}`
	num_chars_max_ext=5
	new_extension="html"

	if [[ "$num_chars_ext" -gt "$num_chars_max_ext" ]]; then
		#Verifying if basename contains a "dot" symbol in order to avoid renaming hidden files
		contains `basename $file` "." || echo "Rename: ".`basename $file`
		contains `basename $file` "." || mv $file $file.$new_extension

	#else
		#echo "no"
	fi
done

That’s it!

Be happy with your code!

Leave a Reply

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