Atoof
Atoof

Reputation: 11

adding a column which derive from another column by an expression with awk

How can I add a column after first, which has values calculate from an expression. this expression has a form: (vn+v0)*vl where v0 and vl is the first and last element of 3th column, respectively and vn is nth element of that column. for example we have a text table:

1 2 3 4
10 20 30 40 
100 200 300 400

it should be converted to

1  1800 3 4
10  9900 30 40 
100 180000 300 400

thanks

Upvotes: 0

Views: 65

Answers (1)

Kent
Kent

Reputation: 195059

as the rule you defined in your question, the number in the last line should not be 180000. it should be (300+3)*300=90900

this awk line could work for you:

 awk 'NR==FNR{c[NR]=$3;l=NR;next}{$2=($3+c[1])*c[l]}7' file file

output is:

kent$  awk 'NR==FNR{c[NR]=$3;l=NR;next}{$2=($3+c[1])*c[l]}7' file file
1 1800 3 4
10 9900 30 40
100 90900 300 400

EDIT

OP wants add a new column after the first:

kent$  awk 'NR==FNR{c[NR]=$3;l=NR;next}{$2=($3+c[1])*c[l]" "$2}7' file file
1 1800 2 3 4
10 9900 20 30 40
100 90900 200 300 400

Upvotes: 1

Related Questions