Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subtract the values of two columns using awk or bash

Tags:

bash

awk

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
like image 724
user1606717 Avatar asked Aug 17 '12 11:08

user1606717


1 Answers

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)

like image 161
Levon Avatar answered Oct 20 '22 20:10

Levon