7

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
knittl
  • 246,190
  • 53
  • 318
  • 364
ICTdesk.net
  • 173
  • 1
  • 1
  • 4

3 Answers3

16

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)

knittl
  • 246,190
  • 53
  • 318
  • 364
16

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'
potong
  • 55,640
  • 6
  • 51
  • 83
  • 2
    The Apple/OSX version is: `md5 * | sed -e 's/MD5 (\([^.]*\)\(.[^)]*\)) = \(.*\)$/mv -v "\1\2" \3\2/' | sh` – fnl May 23 '16 at 07:53
  • If you have a large number of files on OSX: `ls -1 | while read file; do md5 "$file" | sed -e 's/MD5 (\(.*\)\(\.[^\d]*\)) = \(.*\)$/mv -v "\1\2" "\3\2"/' | sh ; done` ( This extends from @fnl's version to handle a case where I had a timestamp with a decimal in some file names ) – ggranum Nov 19 '18 at 21:01
  • This solution may not be able to handle filenames with spaces, beware. I have a few files that doesn't work with this and they all have spaces – Takase Jun 07 '20 at 07:48
0
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

Zsolt Botykai
  • 50,406
  • 14
  • 85
  • 110