Jdizzle
Jdizzle

Reputation: 35

How to subtract one csv value from another on bash?

I have two csv files: cs1.csv

total, , 1,2,3,4,5

and cs2.csv:

total, , 1,1,1,1,1

So im trying to subtract cs2.csv from cs1.csv, how would i do so? Also should i turn the 'total' and blank variables to numbers to do so?

I have attempted to do:

paste c1.csv c2.csv | awk '{print $1 - $2 }' > result.csv

but the result turns up as 0.

EDIT : expected output should be:

total, , 0,1,2,3,4

or

, , 0,1,2,3,4

or so on...

Basically, the first two variables do not really matter as long as I get the numbers behind it.

Upvotes: 1

Views: 1011

Answers (2)

Mark Setchell
Mark Setchell

Reputation: 207465

If it really is as you show it, you can do it in straight bash if you are happier with a simple approach:

IFS=, read _ _ x1 x2 x3 x4 x5 < cs1.csv            # read cs1.csv ignoring first two values and using comma as IFS (input field separator)
IFS=, read _ _ y1 y2 y3 y4 y5 < cs2.csv            # read cs2.csv ignoring first two values and using comma as IFS (input field separator)

echo $((x1-y1)),$((x2-y2)),$((x3-y3)),$((x4-y4)),$((x5-y5))

Sample Output

0,1,2,3,4

I don't want to mislead you though, so you should be aware that bashcannot deal readily with floats/reals (non-integers) and this approach is not that flexible if the number of fields changes - but if you are learning, it may be good enough.

If you wanted to deal with real numbers, you could outsource the maths to bc by replacing the last line with:

bc <<< "$x1 - $y1; $x2 - $y2; $x3 - $y3; $x4 - $y4; $x5 - $y5"

Upvotes: 1

anubhava
anubhava

Reputation: 785156

You can use awk:

awk 'BEGIN{FS=OFS=","} NR==FNR{for (i=1; i<=NF; i++) a[i]=$i; next} 
{for (i=1; i<=NF; i++) if ($i+0==$i) $i-=a[i]} 1' {cs2,cs1}.csv

total, ,0,1,2,3,4

$i+0==$i checks if a column value is numeric.

Upvotes: 2

Related Questions