user1606717
user1606717

Reputation: 153

subtract the values of two columns using awk or bash

I have some text files as shown below. I would like to subtract the values of column 2 and 4 and need to create a new column to the output.

co1  co2   co3    co4

r1  15.2  13.0   21.4
r2  23    15     15.7
r3  14    8      12

desired output

co1  co2   co3   co4   diff.    

r1  15.2  13.0   21.4   -6.2
r2  23    15     15.7   7.3
r3  14    8      12     2

Upvotes: 11

Views: 40334

Answers (3)

Peter van Galen
Peter van Galen

Reputation: 480

The one-liner by Taku Miyakawa can be simplified if you don't have a header:

awk '{ $5 = $2 - $4 } 1' input.txt > inputdiff.txt

Or with tab separation:

awk 'BEGIN { OFS = "\t" } { $5 = $2 - $4 } 1' input.txt > inputdiff.txt

Upvotes: 11

Levon
Levon

Reputation: 143047

Note: You could put the awk commands all on one line, but this is tidier (plus more transparent and easier to modify if need be).

This so.awk script:

NR==1{print $0, "   diff.\n"}
NR>2{printf("%s\t%5.1f\n", $0, $2-$4)}

gives:

co1  co2   co3   co4     diff.

r1  15.2  13.0   21.4    -6.2
r2  23    15     15.7     7.3
r3  14    8      12       2.0

Given your data in file data.txt issue this command:

 awk -f so.awk data.txt

(You may have to adjust the formatting to fit your exact needs)

Upvotes: 14

Taku  Miyakawa
Taku Miyakawa

Reputation: 141

This one-liner works:

awk 'NR == 1 { $5 = "diff." } NR >= 3 { $5 = $2 - $4 } 1' <input.txt

It gives:

co1 co2 co3 co4 diff.

r1 15.2 13.0 21.4 -6.2
r2 23 15 15.7 7.3
r3 14 8 12 2

If you want to separate fields by tabs, this is wat you want:

awk 'BEGIN { OFS = "\t" } NR == 1 { $5 = "diff." } NR >= 3 { $5 = $2 - $4 } 1' <input.txt

Upvotes: 12

Related Questions