Rename file 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 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.

We use find to list all files in our current directory:

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

For each argument (referenced by $1), we want to execute the mv command. For the sake of example, we’ll use echo instead of mv:

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

We use ${1%.*} to get the basename:

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

We use ${1##*.} to get the extension:

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

We use $(md5 -q $1) to generate the MD5 hash:

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

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

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