Rename files to md5 sum + extension (BASH)

后端 未结 3 1130
心在旅途
心在旅途 2020-12-10 06:49

I need some help with a bash script. Script needs to rename all files in a directory to its md5 sum + extension.

I have found the bash script below, but it needs to

相关标签:
3条回答
  • 2020-12-10 07:35

    This might work for you:

    # mkdir temp && cd temp && touch file.{a..e}
    # ls
    file.a  file.b  file.c  file.d  file.e
    # md5sum * | sed -e 's/\([^ ]*\) \(.*\(\..*\)\)$/mv -v \2 \1\3/' | sh
    `file.a' -> `d41d8cd98f00b204e9800998ecf8427e.a'
    `file.b' -> `d41d8cd98f00b204e9800998ecf8427e.b'
    `file.c' -> `d41d8cd98f00b204e9800998ecf8427e.c'
    `file.d' -> `d41d8cd98f00b204e9800998ecf8427e.d'
    `file.e' -> `d41d8cd98f00b204e9800998ecf8427e.e'
    

    Or GNU sed can do it even shorter:

    # md5sum * | sed -e 's/\([^ ]*\) \(.*\(\..*\)\)$/mv -v \2 \1\3/e'
    
    0 讨论(0)
  • 2020-12-10 07:38
    find . -type f -exec mv \{\} "`md5sum \{\} | sed 's/ .*//'`.`echo \{\} | awk -v FS='.' '{print $NF}'\" 
    

    Or something like this will do :-). Actually, I'd recommend to add a filter to the filenames for the find command as it will fail on files without a . in their name.

    HTH

    0 讨论(0)
  • 2020-12-10 07:46

    I would go this route:

    for F in $DIR/*.*; do
      mv "$F" "$(md5sum "$F" | cut -d' ' -f1).${F##*.}";
    done
    

    Use ${F#*.} to get everything after the first period, e.g. tar.gz instead of gz (depends on your requirements)

    0 讨论(0)
提交回复
热议问题