Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux 用硬链接替换重复文件的函数_Linux_Bash - Fatal编程技术网

Linux 用硬链接替换重复文件的函数

Linux 用硬链接替换重复文件的函数,linux,bash,Linux,Bash,我需要编写一个bash脚本,迭代指定目录的文件,并用硬链接替换重复的文件 到目前为止,我已经遍历了这些文件,并将文件名存储在一个数组中 现在,我需要遍历该数组并检查每个文件是否有重复项。我使用的相关代码如下所示: #"files" is the array with all the file names #"fileNum" is the size of the array ... for((j=0; j<$fileNum; j++)) #for every f

我需要编写一个bash脚本,迭代指定目录的文件,并用硬链接替换重复的文件

到目前为止,我已经遍历了这些文件,并将文件名存储在一个数组中

现在,我需要遍历该数组并检查每个文件是否有重复项。我使用的相关代码如下所示:

#"files" is the array with all the file names
#"fileNum" is the size of the array

...

for((j=0; j<$fileNum; j++))             #for every file
do
    if [ -f "$files[$j]" ]          #access that file in the array
    then
        for((k=0; k<$fileNum; k++))     #for every other file
        do
            if [ -f "$files[$k]" ]      #access other files in the array
            then
                test[cmp -s ${files[$j]} ${files[$k]}]      #compare if the files are identical
                [ln ${files[$j]} ${files[$k]}]          #change second file to a hard link
            fi
...
#“files”是包含所有文件名的数组
#“fileNum”是数组的大小
...

对于((j=0;j首先,不要在所有文件上迭代两次,否则您将对每对文件进行两次比较,并将文件与自身进行比较。其次,
(())
中不需要美元符号。最后,我认为您无法正确访问数组,因此
[-f]
总是失败,因此不会发生任何事情。请注意,这也需要更改第一个循环(使用
[-f]
时的数组表示法)

第二个循环应该是这样的:

for((k=j+1; k<fileNum; k++)); do
    if [ -f ${files["$k"]} ]; then
        cmp ${files["$j"]} ${files["$k"]}
        if [[ "$?" -eq 0 ]]; then
            rm  ${files["$k"]}
            ln ${files["$j"]} ${files["$k"]}
        fi
    fi
done

更新,如果不正确,
rm
另一个文件。我只是猜测要删除哪一个哈哈。-如果答案符合您的喜好,请不要忘记接受并投票。顺便说一句,您也可以使用
ln-f
自动删除目标文件(如果存在的话)!告诉我,出现了什么问题?尝试
if[cmp b c];然后echo'equal';否则echo'notequal';fi
-哪些文件失败?尝试添加
echo${files[“$j”]}${files[“$k”]}
cmp
前面的行。这是一个很好的提示,添加
echo
语句来检查进度和调试。投票支持只显示代码的相关部分。问得好!
for((k=j+1; k<fileNum; k++)); do
    if [ -f ${files["$k"]} ]; then
        cmp ${files["$j"]} ${files["$k"]} && ln -f ${files["$j"]} ${files["$k"]}
    fi
done