2009年9月24日星期四

Unix shell script for removing duplicate files

The following shell script finds duplicate (2 or more identical) files and outputs a new shell script containing commented-out rm statements for deleting them (copy-paste from here):
OUTF=rem-duplicates.sh; echo "#! /bin/sh" > $OUTF; find "[email protected]" -type f -exec md5sum {} \; | sort --key=1,32 | uniq -w 32 -d --all-repeated=separate | sed -r 's/^[0-9a-f]*( )*//;s/([^a-zA-Z0-9./_-])/\\\1/g;s/(.+)/#rm \1/' >> $OUTF; chmod a+x $OUTF; ls -l $OUTF

You then have to edit the file to select which files to keep - the script can't safely do it automatically!

If you prefer a C program, try e.g. fdupes (may also be available in the the repository of you favorite Linux distribution). For a GUI based solution, fslint might do it for you.

The code was written for Debian GNU/Linux and has been tested with Bash, Zsh and Dash. Needless to say, you are welcome to do whatever you like with it as long as you don't blame me for disasters... (released in Public Domain)

Thanks to Leendert Meyer, Uriel, Patrick-Emil Zörner and several others for testing and improving the script.

The same script in a more readable form:

OUTF=rem-duplicates.sh;
echo "#! /bin/sh" > $OUTF;
find "[email protected]" -type f -exec md5sum {} \; |
sort --key=1,32 | uniq -w 32 -d --all-repeated=separate |
sed -r 's/^[0-9a-f]*( )*//;s/([^a-zA-Z0-9./_-])/\\\1/g;s/(.+)/#rm \1/' >> $OUTF;
chmod a+x $OUTF; ls -l $OUTF



Example output



#! /bin/sh
#rm ./gdc2001/113-1303_IMG.JPG
#rm ./reppulilta/gdc2001/113-1303_IMG.JPG

#rm ./lissabon/01-01-2001/108-0883_IMG.JPG
#rm ./kuvat\ reppulilta/lissabon/01-01-2001/108-0883_IMG.JPG

#rm ./gdc2001/113-1328_IMG.JPG
#rm ./kuvat\ reppulilta/gdc2001/113-1328_IMG.JPG


Explanation




  1. write output script header

  2. list all files recursively under current directory

  3. escape all the potentially dangerous characters with xargs

  4. calculate MD5 sums

  5. find duplicate sums

  6. strip off MD5 sums and leave only file names

  7. escape strange characters from the filenames

  8. write out commented-out delete commands

  9. make the output script writable and ls -l it


没有评论:

发表评论