Algorithms, Blockchain and Cloud

How to Change All Filenames to Lowercase Under BASH for Files under Directories and Sub-Directories


Linux BASH shell is very powerful. You must have heard of “where there is a shell, there is a way”. We can write a script that recursively changes all the filenames to lowercases for specified folders and their sub directories.

#tolower.sh

convert() 
{
	mv $1 `dirname $1`/`basename $1 | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
}

[ $# = 0 ] && { echo "Usage: tolower item1 item2 ..."; exit; }

for item in $*
do
	[ "`dirname $item`" != "`basename $item`" ] && {
		[ -d $item ] && {
			for subitem in `ls $item`
			do
				tolower $item/$subitem
			done
		}
		convert $item
	}
done

You can swap the paramters of tr to convert to uppercases.

mv $1 `dirname $1`/`basename $1 | tr 'abcdefghijklmnopqrstuvwxyz'` 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

At least 1 parameter is required otherwise the message of usage will be printed. This is the same of using if then; done but this is more elegant and concise. See this post for compound command.

[ $# = 0 ] && { echo "Usage: tolower item1 item2 ..."; exit; }

[ -d $item ] checks for directories and the recursive calls are:

for subitem in `ls $item`
do
	tolower $item/$subitem
done

–EOF (The Ultimate Computing & Technology Blog) —

223 words
Last Post: How to Show System Environment Variables using VBScript/JScript under Window Scripting Host
Next Post: BASH Script to Solve 8 Queen Problem

The Permanent URL is: How to Change All Filenames to Lowercase Under BASH for Files under Directories and Sub-Directories (AMP Version)

Exit mobile version