Help with ask adding columns

Hello,

I am using AWK in UBUNTU 12.04.

I have a dataset as follows:

1 2 12 1 4 1 4 1 7 9 4 6 
1 2 4 5 7 8 45 7 4 5 7 5

What I want to do is to add the values of some columns to each other and print it in the same file as the new column while omitting the previous two columns to have output as follows as an example:

1+4+4=9 2+1+6=9

So:

9 9 12 1 4 1 7 9 
53 14 4 5 7 8 4 5

thank you very much

Assuming your file structure as it is.

Try....

 awk '{ $1=$1+$7+$(NF-1);$2=$2+substr($8,1,1)+$NF;$7=$8="";gsub(" +"," ",$0);NF-=2;}1' file
1 Like

Thanks a lot. Could you please explain these two parts of the code:

substr($8,1,1)
gsub(" +"," ",$0)
NF-=2;

I think you have edited your previous input....:smiley:

As per your previous input i have considered as you want only first digit of $8 .

That's why i used substr()

substr($8,1,1) - Prints only first digit of $8

gsub(" +"," ",$0) - Replaces multiple spaces with single space. To get the FS as single space.:slight_smile:

NF-=2 - Here we need to remove last two numbers. That's why we have edited NF to NF-2 . So NF is reduced by 2.

As per your current input you can remove that substr() :smiley:

use

awk '{ $1=$1+$7+$(NF-1);$2=$2+$8+$NF;$7=$8="";gsub(" +"," ",$0);NF-=2;}1' file
1 Like