How to compare content of two files?

7,122

Solution 1

If all you need to know is whether the files differ or not, use cmp. Or, more precisely:

if cmp "$FILE1" "$FILE2"; then
  echo same
else
  echo different
fi

(Or whatever you need to do when they're equal/not-equal). cmp should be present on any posix-like system, works on both binary and text files, and returns immediately when it finds a difference, which is about as fast as you're going to get. (Also, because it's not line-aware, it doesn't waste time finding line-endings.)

Solution 2

diff command should do the job. Use it with -q option to print only the file names which differ in their contents.

diff -q file1 file2

If you want to entire files in a pair of directory, add -r option

diff -r -q dir1 dir2

Refer documentation for more details by typing man diff

Share:
7,122

Related videos on Youtube

mosh
Author by

mosh

Updated on September 18, 2022

Comments

  • mosh
    mosh over 1 year

    I got a mission to compare the content of hundreds of pair files. I have to quickly compare each pair and to provide an answer if that pair is equal (in content) or not. The files could be text or binary files. Can you help me please?

    1. I'm looking for a command that works on ALL UNIX \ Linux editions
    2. I'd prefer to use the most efficient command (in regards to time and performance)
    3. I'd prefer a command that supports text and binary files
    4. I'd prefer a command that is installed as part of the OS (not a 3rd-party)

    Thank you!

    • Dolarious
      Dolarious over 10 years
      I'd recommend diff - man diff