Lei Zhang
Lei Zhang

Reputation: 103

awk field count arithmetic

I am trying to do a simple column addition of column $i and column $((i+33)), I am not sure the syntax is correct or not.

Two files are first pasted together, and then a column addition across two files are performed.

Thank you!

paste DOS.tmp DOS.tmp2 | awk '{ printf "%12.8f",$1 OFS; for(i=2; i<33; i++) printf "%12.8f",$i+$((i+33)) OFS; if(33) printf "%12.8f",$33+$66; printf ORS}' >| DOS.tmp3

Upvotes: 0

Views: 111

Answers (2)

randomir
randomir

Reputation: 18687

In awk, unlike in bash, variable expansion does not require a dollar sign ($) in front of the variable name. Variables are defined like a = 2 and used like print a.

Dollar sign ($) is used to refer to (input) fields. So, print $1 will print the first field, and print $a will print the field referenced by variable a, in our case the second field. Similarly, print $a, $(a+3) will print the second and fifth field (separated by the OFS).

All this taken together, makes your program look like:

awk '{ out = sprintf("%12.8f", $1)
       for (i=2; i<=33; i++) out = out sprintf("%s%12.8f", OFS, $i+$(i+33))
       print out }' numbers

Notice we use sprintf to print all values to the output line variable out first, concatenating like out = out val, and then printing the complete output record with print.

Upvotes: 1

scinart
scinart

Reputation: 466

Are you trying to add column i in file_1 and file_2? In this case, I provide an example:

paste <(seq -s' ' 33) <(seq -s' ' 33) | awk '{ for(i=1; i<=33; i++) { printf "%f",$i+$((i+33)) ; if(i!=33) printf OFS;} printf ORS}'

Upvotes: 1

Related Questions