在 Unix/Linux 中判断两个文件是否具有相同内容的最快方法
linuxoperating systemopen source更新于 2026/1/11 23:07:17
假设我们在名为 dir1 的目录中有两个文件,并且这两个文件最初都是不同的。不同之处在于它们包含的文本不一样。
文件夹中的文件 −
immukul@192 dir1 % ls -ltr total 16 -rw-r--r-- 1 immukul staff 7 Jul 7 10:37 2.txt -rw-r--r-- 1 immukul staff 8 Jul 8 19:05 3.txt
第一个文件 (2.txt) 的内容如下所示 −
immukul@192 dir1 % cat 2.txt orange
第二个文件 (2.txt) 的内容如下所示 −
immukul@192 dir1 % cat 3.txt uorange
我们可以轻松使用 diff 命令来检查它们是否有差异。请考虑以下命令 −
diff 2.txt 3.txt
输出
1c1 < orange --- > uorange
但如果文件内容完全相同,则 diff 命令将不会返回任何输出。
在这种情况下,建议使用 cmp 命令。cmp 命令是一个用于比较两个文件的 Linux 实用程序命令。
命令
cmp --silent 2.txt 3.txt || echo "Difference in Files"
输出
immukul@192 dir1 % cmp --silent 2.txt 3.txt || echo "Difference in Files" Difference in Files
相关文章
有用资源
linux 参考教程 - 该教程包含有关 linux 的更多信息:https://www.cainiaomax.com/linux/

