AWK help ! or others ways to do it!

Hi!

I really need your help!

I need to operate the columns separate by ',' of a file with this structure

a1,a2,a3
b1,b2,b3,b4,b5
c1,c2
d1,d2,d3
e1
....

and I want the result of this subtractions

a1-a1,a2-a1,a3-a1
b1-b1,b2-b1,b3-b1,b4-b1,b5-b1
c1-c1,c2-c1
d1-d1,d2-d1,d3-d1
e1-e1

For example, if the file is

43805414,43805643,43805660,43805688,43805771,43805788,43805876,
116842150,116844494
117072160,117072559,117073456
115850458,115850499,115650901,115651050
115538171,

The desired result would be

0,229,246,274,357,374,462
0,2344 
0,399,1296 
0,41 
0 

I'm a beginer at awk, I tried this code

awk -F, '{print $1-$1, $2-$1, $3-$1, $4-$1, $5-$1, $6-$1, $7-$1}' ./InputFile

But the numbers of columns is variable, some lines has many columns and I don't want the negative results. Besides, if it possible, I want the output separate by ','

Thanks a lot!!!!!!!!!

nawk -F, '{for(i=1;i<=NF;i++) printf("%s%c", $i-$1, (i==NF)?ORS:FS)}' myFile

What should be done with the negative numbers?

Try:

awk -F',' '{for(i=1;i<NF;i++) {printf ($i>=$1)?$i-$1 FS:""};print ($NF>$1)?$NF-$1:""}'

To skip negative results:

awk -F',' '{A="";for(i=NF;i;i--)if($i-$1>=0)A=($i-$1)(A?","A:""); print A}'
1 Like

Thanks you!

I tested both codes with this file:

1,2,3,4,5
2,5,6,45
3,56,100,1000
2,

with the vgersh99's code I get

splicing@splicing-desktop:~/awk$ nawk -F, '{for(i=1;i<=NF;i++) printf("%s%c", $i-$1, (i==NF)?ORS:FS)}' ./c12.2
0,1,2,3,4
0,3,4,43
0,53,97,997
0,-2

Almost perfect!! but I seems that when there are only 1 column, produce negative results :(...
Because the first column has the minor number, I don't expect negative results. If you give me some way to filter out the negative results, I will thanks you a lot!

with the yinyuemi's code I get

 
splicing@splicing-desktop:~/awk$ awk -F',' '{for(i=1;i<NF;i++) {printf $i-$1 FS};print $NF=$1}' ./c12.2
0,1,2,3,1
0,3,4,2
0,53,97,3
0,2

This is not what I need :(.
I need subtracts column 1 against the others columns. Thanks you anyway.

nawk -F, '{for(i=1;i<=NF;i++) printf("%s%c", ($i=="")?"":$i-$1, (i==NF)?ORS:FS)}' myFile
# or to filter out ALL negative results
nawk -F, '{for(i=1;i<=NF;i++) printf("%s%c", ($i<$1)?"":$i-$1, (i==NF)?ORS:FS)}'
1 Like

Chubler_XL's code works perfect!

thanks you guys!

Hi geparada88,

I have changed my code as the above, please try it:>

Best,

Y

1 Like
nawk -F, '{for(i=1;i<=NF;i++) printf("%s%c", ($i=="")?"":$i-$1, (i==NF)?ORS:FS)}' ./file

works!!!
thanks vgersh99 :slight_smile:

---------- Post updated at 05:14 PM ---------- Previous update was at 05:05 PM ----------

yinyuemi

It's works nice!!

Cheers

$ ruby -F"," -ane  'puts $F[0..-1].map{|x| x.to_i-$F[0].to_i }.select{|y|y>=0?y:nil}.join(",")' file
0,229,246,274,357,374,462
0,2344
0,399,1296
0,41
0

awk -F [,] '{a=$1;x=$1-a;for (i=2;i<=NF;i++){x=x","$i-a}print x}'