2016-11-29 58 views
-1

最终,我想摆脱重复条目显示我的数组的可能性。我这样做的原因是因为我正在研究比较两个目录,搜索和删除重复文件的脚本。潜在的重复文件存储在一个数组中,并且只有与原始文件具有相同的名称和校验和才能删除这些文件。所以如果有重复的条目,我会遇到一些小错误,其中md5试图找到不存在的文件的校验和(因为它已经被删除),或者rm试图删除已经被删除的文件。如何对数组的内容进行排序?

这是脚本的一部分。

compare() 
{ 

read -p "Please enter two directories: " dir1 dir2 

if [[ -d "$dir1" && -d "$dir2" ]]; then 
    echo "Searching through $dir2 for duplicates of files in $dir1..." 
else 
    echo "Invalid entry. Please enter valid directories." >&2 
    exit 1 
fi 

#create list of files in specified directory 
while read -d $'\0' file; do 
    test_arr+=("$file") 
done < <(find $dir1 -print0) 

#search for all duplicate files in the home directory 
#by name 
#find checksum of files in specified directory 
tmpfile=$(mktemp -p $dir1 del_logXXXXX.txt) 


for i in "${test_arr[@]}"; do 
    Name=$(sed 's/[][?*]/\\&/g' <<< "$i") 

    if [[ $(find $dir2 -name "${Name##*/}" ! -wholename "$Name") ]]; then 
     [[ -f $i ]] || continue 
     find $dir2 -name "${Name##*/}" ! -wholename "$Name" >> $tmpfile 
     origray[$i]=$(md5sum "$i" | cut -c 1-32) 
    fi 
done 

#create list of duplicate file locations. 
dupe_loc 

#compare similarly named files by checksum and delete duplicates 
local count=0 
for i in "${!indexray[@]}"; do 
    poten=$(md5sum "${indexray[$i]}" | cut -c 1-32) 
    for i in "${!origray[@]}"; do 
     if [[ "$poten" = "${origray[$i]}" ]]; then 
      echo "${indexray[$count]} is a duplicate of a file in $dir1." 
      rm -v "${indexray[$count]}" 
      break 
     fi 
    done 
    count=$((count+1)) 
done 
exit 0 
} 

dupe_loc是以下功能。

dupe_loc() 
{ 
if [[ -s $tmpfile ]]; then 
    mapfile -t indexray < $tmpfile 
else 
    echo "No duplicates were found." 
    exit 0 
fi 
} 

我想解决这个问题是使用的sortuniq命令处置阵列中的重复条目的最佳方式。但即使有流程替代,我在尝试这样做时也会遇到错误。

+1

你能进一步简化问题吗?假设你有两个带有文件的目录,并且你想要一个只有来自两个目录的唯一内容的第三个目录? – NinjaGaiden

+1

'sort -u -kN,M'应该足够了。对于这个问题,请阅读http://stackoverflow.com/help/mcve,然后再发布更多Q​​.祝你好运。 – shellter

+0

一个更简单的方法是用文件名(无路径)填充'test_arr',一旦你填充了'test_arr',只需循环名称和'test',如果dir2中有一个文件名为。 'test_arr + =(“$ {file ## * /}”)',然后'declare -a dups;因为我在“$ {test_arr [@]}”;做[-f“$ dir2/$ i”] && dups + =(“$ i”); done'你现在有'dups'中的重复列表。 –

回答

0

第一件事是第一件事。 Bash数组排序已经在这里回答:How to sort an array in BASH

这就是说,我不知道对数组进行排序会有很大的帮助。看起来更简单的解决方案就是将你的md5检查和rm语句包装在if语句中:

if [ -f origarr[$i]} ]; do #True if file exists and is a regular file. 
    #file exists 
    ... 
    rm ${origarr[$i]} 
fi