Search code examples
phpbashmd5sum

How to rename files inside folder to its corresponding md5sum?


I have large samples in a folder with plain names and file names with spaces also and i want to renames all the files to its corresponding md5sum.

I tried this logic for f in $(find /home/SomeFolder/ -type f) ;do mv "$f" "$(md5sum $f)";done

But this is not working properly with some error like mv: cannot move to indicating no such directory.

Also i tried this logic Rename files to md5 sum + extension (BASH) and tried this for f in $(find /home/Testing/ -type f) ;do echomd5sum $f;mv $f /home/Testing/"echomd5sum $f``"; done; ` But it is not working.

Any suggestions to solve this.

I want to replace a file to its md5sum name without any extension

sample.zip --> c75b5e2ca63adb462f4bb941e0c9f509

c75b5e2ca63adb462f4bb941e0c9f509c75b5e2ca63adb462f --> c75b5e2ca63adb462f4bb941e0c9f509

file name with spaces.php --> a75b5e2ca63adb462f4bb941e0c9f509


Solution

  • See Why you shouldn't parse the output of ls or find in a for-loop, ParsingLs,

    If you have file names with spaces also recommend using -print0 option of GNU findutils for the job which embeds a \0 character after file name with read with a null delimiter as below.

    Run the script below inside /home/SomeFolder and use find from the current directory as

    #!/bin/bash
    
    while IFS= read -r -d '' file
    do
        mv -v "$file" "$(md5sum $file | cut -d ' ' -f 1)"
    done< <(find . -mindepth 1 -maxdepth 1 -type f -print0)
    

    The depth options ensure the current folder . is not included in the search result. This will now get all the files in your current directory ( remember it does not recurse through sub-directories) and renames your file with the md5sum of the filenames.

    The -v flag in mv is for verbose output ( which you can remove) for seeing how the files are to be renamed as.