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

有一次,我在使用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.这个算法对相同路径下的文件实行两两对比,个人觉得算法效率还有提升空间。欢迎各位有更好想法的留言讨论。  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值