Rename files with MD5 hash


Rename single file

To generate an MD5 hash based on the file content:

$ md5 -q file.txt
d41d8cd98f00b204e9800998ecf8427e

Then to rename the file with its hash:

$ mv file.txt "file.$(md5 -q file.txt).txt"
$ ls
file.d41d8cd98f00b204e9800998ecf8427e.txt

Rename multiple files

To rename each file with its MD5 hash:

$ find . -type f -exec bash -c 'mv "${1%.*}.$(md5 -q $1).${1##*.}"' bash {} \;

Let’s break down what’s happening.

1. We’re using find to list all the files in directory . (current):

$ find . -type f
./file1.txt
./file2.txt

2. For each argument (referenced by $1), you can execute a bash command with -exec bash -c:

$ find . -type f -exec bash -c 'echo $1' bash {} \;

3. Get the file basename with ${1%.*}:

$ find . -type f -exec bash -c 'echo ${1%.*}' bash {} \;

4. Get the file extension with ${1##*.}:

$ find . -type f -exec bash -c 'echo ${1##*.}' bash {} \;

5. Generate the MD5 hash with $(md5 -q $1):

$ find . -type f -exec bash -c 'echo $(md5 -q $1)' bash {} \;

6. Finally, concatenate the string with . and rename each file with mv:

$ find . -type f -exec bash -c 'mv $1 "${1%.*}.$(md5 -q $1).${1##*.}"' bash {} \;

To rename files with spaces, wrap $1 in double quotes (credit goes to Andreas Sahlbach):

$ find . -type f -exec bash -c 'mv "$1" "${1%.*}.$(md5 -q "$1").${1##*.}"' bash {} \;


If you enjoyed this post, please consider supporting this site!