Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename files to md5 sum + extension (BASH)

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 be changed so that it will add the extension.

md5sum * | sed 's/^\(\w*\)\s*\(.*\)/\2 \1/' | while read LINE; do mv $LINE; done
like image 593
ICTdesk.net Avatar asked Nov 20 '11 13:11

ICTdesk.net


2 Answers

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'
like image 105
potong Avatar answered Oct 18 '22 07:10

potong


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)

like image 34
knittl Avatar answered Oct 18 '22 07:10

knittl