Shell Scripts to Manipulate The File Name Extensions

The following snippets show how to change the file name extensions on multiple files on UNIX machines. Other commands like rename and mmv might offer alternatives when they are available on the systems. The scripts below use shell’s parameter expansion to operate on multiple files.

% in below scripts match shortest from the end of the string.

%% matches longest from the end

# shortest from the beginning

## longest from the beginning

test command controls if a rename should occur or not.

The following script ensures that all the files that match a specific pattern have “.pgp” extension. This will not touch a matching file which already has “.pgp” extension. Note that if a non “.pgp” extension already exists, it still appends “.pgp”.

#!/usr/bin/ksh
for filename in pattern*
do
test "${filename}"="${filename%.pgp}"&& mv "$filename""${filename}.pgp"done

This can be easily tweaked to change one extension to another. The below script changes extension to “.gpg” on all “.pgp” files that match a pattern.