2

Is there a (command line) tool to calculate percentage change between two files of the same format full of numbers?

Example:

File A:

100 100

File B:

150 70

Invocation:

$ calc_perc_change A B
+50% -30%
2
  • 1
    I doubt, but this is very easily scriptable. The problem is you haven't provided your system.
    – Destroy666
    Commented Dec 8, 2023 at 6:56
  • It is rather simply done in a scripting language on linux/unix/mac. I recommend posting this on on Stack Overflow, tag it with [bash], [awk] and [perl]. Also, provide an attempt at coding it, even a simple one. If you file has more rows and columns, give a corresponding example. Good luck! Commented Dec 8, 2023 at 15:33

1 Answer 1

2

On UNIX-like system, such as UNIX, Linux or macOS, use this Perl script:

perl -le '
( $old, $new ) =  @ARGV;
chomp ( @old = map { split "\t", $_ } do { local @ARGV = $old; <> } );
chomp ( @new = map { split "\t", $_ } do { local @ARGV = $new; <> } );
@pct_chg = ();
for $i ( 0 .. $#old ) {
    $pct_chg[$i] = 100 * ( $new[$i] - $old[$i] ) / abs( $old[$i] );
}
print join "\t", map { sprintf qq{%+d%}, $_ } @pct_chg;
' old.tsv new.tsv > pct_chg.tsv

I am assuming TAB-delimited input and output.

Example inputs:

echo '100\t100' > old.tsv
echo '150\t70' > new.tsv

Example output:

+50%    -30%

The Perl script uses these command line flags:
-e : Tells Perl to look for code in-line, instead of in a file.
-l : Strip the input line separator ("\n" on *NIX by default) before executing the code in-line, and append it when printing.

@ARGV : Input file names.
do { local @ARGV = $old; <> } : slurp the input file into an array.
map { split "\t", $_ } : split the elements of the array (here, the array has only 1 element, the input line) into another array on TAB as a separator.
chomp : Remove input line separator, here newline.

See also:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.