用Shell 脚本 实现 相同路径或文件夹下重复文件的查找

来源:互联网 发布:ubuntu edk2 下载 编辑:程序博客网 时间:2024/06/07 18:13

有一次,我在使用Google drive时不小心将已经存放有文件的文件夹设置为了google drive 的专有文件夹。

Google drive 的同步服务将目录中已经存在的文件也下载了下来,而且自动重命名为xxx.(1) 这样的形式。于是有些子目录内存在大量的内容相同,名字不同的文件。


由于我的网盘目录结构复杂,文件数量大,如果手工找出这些重名文件并删除的话很耗费精力。于是自己动手编写了一个shell 脚本程序来帮我的忙。


该脚本通过对比相同路径下的文件内容自动找出相同路径下的重复文件(内容相同)然后将他们按照之前的目录结构 全部复制到当前路径下的DuplicatedFiles 文件夹下。

#!/bin/bash#Delete duplicated files in one directory recursivelyfunction ergodicFolder(){for file in `ls "$1" | tr " " "\?"`dofile=`tr "\?" "\ " <<<$file`local currentDirectory=$1if [ -d "$currentDirectory/$file" ]then ergodicFolder "$currentDirectory/$file"elsecurrentDirectory=$1#local path="$1""/" #get the full directory of the filelocal sourceFile="$file" #get the file namesecho "###Processing in directory: $currentDirectory"for file2 in `ls "$currentDirectory" | tr " " "\?"`dofile2=`tr "\?" "\ " <<<$file2`local targetFile="$file2"local innerPath="$currentDirectory"# If the target file and source file existif [ -f "$innerPath/$targetFile" ]&&[ -f "$innerPath/$sourceFile" ]then#skip the same fileif [ "$targetFile" == "$sourceFile" ]then continue fi#skip the directoryif [ -d "$innerPath/$targetFile" ]then#delete recursively#ergodicFolder "$innerPath$targetFile"continuefi#compare and delete the same file which has long name if [ "`cmp "$innerPath/$sourceFile" "$innerPath/$targetFile"`" == "" ]thenecho "***(""$innerPath/$sourceFile"") is as same as (""$innerPath/$targetFile"")"local longNameFileWithPath="$innerPath/$sourceFile" if [ `expr length "$sourceFile"` -ge `expr length "$targetFile"` ]thenlongNameFileWithPath="$innerPath/$sourceFile" elselongNameFileWithPath="$innerPath/$targetFile" fitar -c "$longNameFileWithPath" | tar x -C "$targetDirectory"echo "delete file:"$longNameFileWithPath" -------" rm "$longNameFileWithPath"fifidonefidone}if [ ! -d "`pwd`/DuplicatedFiles" ]thenmkdir "`pwd`/DuplicatedFiles"fitargetDirectory="`pwd`/DuplicatedFiles"ergodicFolder "$1"




讨论:

1.如果需要对找到的文件进行其他操作请自行替换 tar -c "$longNameFileWithPath" | tar x -C "$targetDirectory"   这一句。

2.其实如果在windows 平台下被自动重名名了的文件,可以用正则表达式匹配文件名以(1)结尾的文件来达到目的。不过只是通过文件名进行判断的话并不是很安全的做法哦。

3.这个算法对相同路径下的文件实行两两对比,个人觉得算法效率还有提升空间。欢迎各位有更好想法的留言讨论。  


原创粉丝点击