1

We have two zip files and would like to compare them.

We're also interested in calculating the percentage difference between them and the file size. Is there a tool that can do this quickly?

2
  • 1
    "percentage difference" is an ambiguous metric. If the original file is 100 bytes long, and is modified by inserting a new byte in the exact middle, is the new file "different" by 1% or 50%? Do you have a different answer if it were text files and it's lines instead of bytes? I.E. compare the results of cmp versus diff.
    – sawdust
    Mar 24, 2013 at 23:09
  • I guess the OP refers to the difference in file size (probably to compare compression rate?) Mar 25, 2013 at 16:11

2 Answers 2

5

You could try a bash script like this one:

#!/bin/bash
SIZE1=$(stat -f "%z" "$1")
SIZE2=$(stat -f "%z" "$2")
PERC=$(bc <<< "scale=2; ($SIZE2 - $SIZE1)/$SIZE1 * 100")
echo "$PERC %"

You then call the script by passing the two files as arguments. I used the command stat -f "%z" "$1" to get the file size and it works on OS X. Depending on your Linux distribution, you might need a different syntax, such as stat -c%s FILENAME, or du -b FILENAME. Try in your console, you should get the number of bytes as output.

Notice that we need to call the program bc because Bash can't do floating point arithmetics.

Of course you can modify the script to fulfill your needs. If you need to compare two compressed files with the uncompressed file you can add another variable and do the desired maths using bc.

2
  • Thanks, Pincopallino. I am trying out with your suggestions.
    – chz
    Apr 6, 2013 at 4:19
  • 1
    With GNU coreutils stat command it would be stat -c "%s" FILENAME Oct 18, 2019 at 18:12
0

You could simply write a Perl script to handle the job. It's less messy than Bash.

Here's an example of such a script. It calculates the file size reduction between the original and compressed file.

#!/usr/bin/env perl
use strict;
use warnings;

die "You must define at least 2 files to compare!\n" unless defined $ARGV[0] && defined $ARGV[1];
die "File $ARGV[0] does not exist!\n" unless -e $ARGV[0];
die "File $ARGV[1] does not exist!\n" unless -e $ARGV[1];

my ($original, $compressed) = (-s $ARGV[0], -s $ARGV[1]);

printf "FILESIZE REDUCTION: %.2f%%\n", ($compressed / $original - 1) * -100;

You execute it like this: perl compare_filesizes.pl my_fancy_javascript.js my_fancy_javascript_min.js

NOTE: You can quote out or remove the die conditions. They're just to remind the user to properly use this script.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .