I produce a huge multi-column output file running some analytical software on angle populations. Sadly, the angles are defines as -180° to 180° and I need 0°-360°.

What I want do to is take this entire input file and replace every negative value with the sum of "360+value" while maintaining every positive value unchanged and printing everything in a tab delimited output file, just like the original input file.

I manage to do this simple enough for 1 column at a time:

awk 'BEGIN {OFS="\t" }; { if($2 < 0) print $1, 360+$2; else print $1, $2}' INPUT > OUTPUT

And I guess that I could do this for every column by including more "ifs" like so:

awk 'BEGIN {OFS="\t" }; { if($2 < 0 || $3 < 0) print $1, 360+$2, 360+$3; else print $1, $2, $3}' INPUT > OUTPUT

Or something similar, however there must be a better way to do this. I tried playing around with "$0" instead though I could not get this to work either.

So is there a nice one-liner (or input script) to check every value in every column if it is less than 0 (a negative number) and print all positive values as is while "adding" 360 to every negative value along the lines of:

awk 'BEGIN {OFS="\t" }; { if($0 < 0) print 360+$0; else print $0}' INPUT > OUTPUT

I do understand that this command wont work though basically this is what I want, maintain the same format as input, if a value is negative then add 360 and print, otherwise just print.

Thank you in advance, all input is appreciated.


You can use a simple for loop e.g.

{for(i=1;i<=NF;i++){if($i < 0) $i+=360}; print}
  • I'll try this as soon as todays meeting is finished... Though it looks like what I was looking for. – gusgrave Jun 13 at 7:55
  • So, I'm just losing the first text filed on the file so #Frame gets replaced with 360 however I assume I could get around this problem with a "skip" (NF>1) or something. Otherwise this solution was just what I had in mind. Thank you – gusgrave Jun 13 at 8:53
  • 1
    @gusgrave if there is a first non-numeric field, you can start the loop from i=2 – steeldriver Jun 13 at 8:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.