Bash脚本比较文件 [英] Bash script to compare files

查看:55
本文介绍了Bash脚本比较文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件夹,里面放着大量的旧照片,其中有很多重复的照片.手动对其进行分类需要很长时间,因此我想利用这个机会使用bash.

I have a folder with a ton of old photos with many duplicates. Sorting it by hand would take ages, so I wanted to use the opportunity to use bash.

现在我有了代码:

#!/bin/bash

directory="~/Desktop/Test/*"
for file in ${directory};
do
    for filex in ${directory}:
    do
        if [ $( diff {$file} {$filex} ) == 0 ]
        then
            mv ${filex} ~/Desktop
            break
        fi
    done
done 

并获取退出代码:

diff: {~/Desktop/Test/*}: No such file or directory
diff: {~/Desktop/Test/*:}: No such file or directory
File_compare: line 8: [: ==: unary operator expected

我试图修改我在网上找到的工作代码,但是它似乎总是会吐出这样的错误.我猜想嵌套的for循环有问题吗?

I've tried modifying working code I've found online, but it always seems to spit out some error like this. I'm guessing it's a problem with the nested for loop?

此外,为什么似乎有不同的方法来调用变量?我看过使用 $ {file},"$ file"和"$ {file}" 的示例.

Also, why does it seem there are different ways to call variables? I've seen examples that use ${file}, "$file", and "${file}".

推荐答案

您在错误的位置放置了 {} :

You have the {} in the wrong places:

if [ $( diff {$file} {$filex} ) == 0 ]

他们应该在:

They should be at:

if [ $( diff ${file} ${filex} ) == 0 ]

(尽管括号现在是可选的),但是您应该在文件名中留出空格:

(though the braces are optional now), but you should allow for spaces in the file names:

if [ $( diff "${file}" "${filex}" ) == 0 ]

现在它根本无法正常工作,因为当 diff 没有发现差异时,它不会产生任何输出(并且您会收到错误,因为 == 运算符不期望左侧没有任何内容).您可以通过双引号 $(…)( if ["$(diff…)" =="] )来修复它,但是您应该简单直接地测试 diff 的退出状态:

Now it simply doesn't work properly because when diff finds no differences, it generates no output (and you get errors because the == operator doesn't expect nothing on its left-side). You could sort of fix it by double quoting the value from $(…) (if [ "$( diff … )" == "" ]), but you should simply and directly test the exit status of diff:

if diff "${file}" "${filex}"
then : no difference
else : there is a difference
fi

,也许为了比较图像,您应该使用 cmp (在静默模式下)而不是 diff :

and maybe for comparing images you should be using cmp (in silent mode) rather than diff:

if cmp -s "$file" "$filex"
then : no difference
else : there is a difference
fi

这篇关于Bash脚本比较文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆