有一次,我在使用Google drive时不小心将已经存放有文件的文件夹设置为了google drive 的专有文件夹。
Google drive 的同步服务将目录中已经存在的文件也下载了下来,而且自动重命名为xxx.(1) 这样的形式。于是有些子目录内存在大量的内容相同,名字不同的文件。
由于我的网盘目录结构复杂,文件数量大,如果手工找出这些重名文件并删除的话很耗费精力。于是自己动手编写了一个shell 脚本程序来帮我的忙。
该脚本通过对比相同路径下的文件内容来自动找出相同路径下的重复文件(内容相同)然后将他们按照之前的目录结构 全部复制到当前路径下的DuplicatedFiles 文件夹下。
#!/bin/bash
#Delete duplicated files in one directory recursively
function ergodicFolder(){
for file in `ls "$1" | tr " " "\?"`
do
file=`tr "\?" "\ " <<<$file`
local currentDirectory=$1
if [ -d "$currentDirectory/$file" ]
then
ergodicFolder "$currentDirectory/$file"
else
currentDirectory=$1
#local path="$1""/" #get the full directory of the file
local sourceFile="$file" #get the file names
echo "###Processing in directory: $currentDirectory"
for file2 in `ls "$currentDirectory" | tr " " "\?"`
do
file2=`tr "\?" "\ " <<<$file2`
local targetFile="$file2"
local innerPath="$currentDirectory"
# If the target file and source file exist
if [ -f "$innerPath/$targetFile" ]&&[ -f "$innerPath/$sourceFile" ]
then
#skip the same file
if [ "$targetFile" == "$sourceFile" ]
then
continue
fi
#skip the directory
if [ -d "$innerPath/$targetFile" ]
then
#delete recursively
#ergodicFolder "$innerPath$targetFile"
continue
fi
#compare and delete the same file which has long name
if [ "`cmp "$innerPath/$sourceFile" "$innerPath/$targetFile"`" == "" ]
then
echo "***(""$innerPath/$sourceFile"") is as same as (""$innerPath/$targetFile"")"
local longNameFileWithPath="$innerPath/$sourceFile"
if [ `expr length "$sourceFile"` -ge `expr length "$targetFile"` ]
then
longNameFileWithPath="$innerPath/$sourceFile"
else
longNameFileWithPath="$innerPath/$targetFile"
fi
tar -c "$longNameFileWithPath" | tar x -C "$targetDirectory"
echo "delete file:"$longNameFileWithPath" -------"
rm "$longNameFileWithPath"
fi
fi
done
fi
done
}
if [ ! -d "`pwd`/DuplicatedFiles" ]
then
mkdir "`pwd`/DuplicatedFiles"
fi
targetDirectory="`pwd`/DuplicatedFiles"
ergodicFolder "$1"
讨论:
1.如果需要对找到的文件进行其他操作请自行替换 tar -c "$longNameFileWithPath" | tar x -C "$targetDirectory" 这一句。
2.其实如果在windows 平台下被自动重名名了的文件,可以用正则表达式匹配文件名以(1)结尾的文件来达到目的。不过只是通过文件名进行判断的话并不是很安全的做法哦。
3.这个算法对相同路径下的文件实行两两对比,个人觉得算法效率还有提升空间。欢迎各位有更好想法的留言讨论。