Unix bash:文件内容的差异

时间:2015-03-30 08:33:55

标签: bash unix awk command diff

我想知道是否有方法或Unix命令知道两个文件的内容是否相同而不考虑订单。

可以说以下两个文件内容必须被视为相同:

  AAAA
  BBBB

  BBBB
  AAAA

提前致谢!

备注:我知道我可以使用 diff md5sum 但据我所知,他们不会考虑我感兴趣的案例。

编辑:因为我需要它来查找成千上万个文件中是否至少有两个文件具有相同的内容我发布了bash脚本我是用@ anishsane给出的答案写的:

#!/bin/bash
for entry in file-*.smt2 
do
  for entry1 in file-*.smt2
  do
    if [ -f "$entry" ] && [ -f "$entry1" ] && [ "$entry" != "$entry1" ]; then
      file1=`sort $entry | md5sum`
      file2=`sort $entry1 | md5sum`

      if [ "$file1" == "$file2" ]
      then
        echo "Files have the same content"
        echo "$entry $entry1"
        echo "$file1"
        echo "$file2"
        exit -2
      else
        echo "Files $entry and $entry1 have NOT the same content"
      fi


   fi
 done
done

1 个答案:

答案 0 :(得分:3)

如果您的文件未排序,您可以使用sort命令对它们进行排序。请注意,此命令不会对文件进行内联排序,而是在stdout上打印文件的已排序版本。

bash有一项名为process substitution的功能。该进程的stdout(或stdin,根据需要)用作/dev/fd/xxx&中的文件句柄。传递给了这个过程。 (diff在下面的示例中。)

结合这两个,你得到了这个使用普通diff

的解决方案
diff <(sort file1) <(sort file2)