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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#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
#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.

1
mv $1 `dirname $1`/`basename $1 | tr 'abcdefghijklmnopqrstuvwxyz'` 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
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.

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

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

1
2
3
4
for subitem in `ls $item`
do
    tolower $item/$subitem
done
for subitem in `ls $item`
do
	tolower $item/$subitem
done

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
240 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

Leave a Reply