I have a column of numbers $2, I would like to add 360 to all numbers that are negative. This method seems a bit convoluted, and does not work (outputs 0):
BEGIN {
A=sprintf("%d", $2);
if(A<0) A=A+360;
BIN[A]++;
}
END { for(A in BIN) print A; }
any help?
$ cat inputfile
1 2
1 -4
5 -7
3 5
10 151
$
$
$ awk '$2<0{$2+=360}'1 inputfile
1 2
1 356
5 353
3 5
10 151
$
$
Thanks!
Could you write it another way including
for{i=0;i<NR;i++}
thanks!
agama
February 17, 2012, 9:14pm
4
chrisjorg:
I have a column of numbers $2, I would like to add 360 to all numbers that are negative. This method seems a bit convoluted, and does not work (outputs 0):
BEGIN {
A=sprintf("%d", $2);
if(A<0) A=A+360;
BIN[A]++;
}
END { for(A in BIN) print A; }
any help?
Your problem is that you're trying to do the work in the BEGIN block, and not for each record. Removing BEGIN
your script should work as you intended.
You also don't need sprintf() like you would if this were C.
awk '{
if( $2+0 < 0 )
$2 += 360
bin[$2]++;
}
END {
for( a in bin)
print a;
}'
@chrisjorg : Why would you want to do this 'another way' by including a for loop?
cat add360.dat | awk '{if($2<0) {$2+=360;print $0} else {print $0}}'