awk - Adding and Subtracting Numbers from 2 Columns

Hi Folks,

I have a file with 2 columns TAB delimited and I want to add '1' to the first column and subtract '-1' from the second column.

What I have tried so far is;

awk -F"\t" '{ $1-=1;$2+=1}1' OFS='\t' file

File

0623	0623
0624	0624
0643	0643
1059	1037
1037	1037
1038	1038
1056	1159

Outputs

622	624
623	625
642	644
1058	1038
1036	1038
1037	1039
1055	1160

This works, as in it will add and subtract as requested. However, AWK is removing the starting digit 0 on the output. I need to keep this as my script is adding and subtracting time.

The two issues I am facing is AWK removing the starting 0 and also if I add '1' to the "time" 1159 my way of counting time will output 1160, where as I would like it to read 1200.

Any help would be met would the greatest of appreciation.

Thank you

awk isn't that easy in respect to either of your questions.

  • if "expr can be represented ... as an exact integer then it is converted to sprintf("%d", expr)." (cf man awk ) So you can't use OFMT or CONVFMT immediately, you need to play dirty tricks with them or use formatted printing of each field.
  • if you want a "carry flag" to apply at a value of 60, again you need to take the scenic route.

How about making the values slightly deviate from an integer so the CONVFMT applies, and to use a conditional assignment for the carry over? Try

awk -F"\t" '{ $1-=1.001;$2+=1.001;$2+=($2%100>=60)?40:0}1' OFS='\t' CONVFMT="%04.0f"  file
0622	0624
0623	0625
0642	0644
1058	1038
1036	1038
1037	1039
1055	1200

Please be aware of the non-integer values if you need to use $1 and $2 in further arithmetics.
The "carry under" for $1 is left as an exercise to the reader. Of course the operations on every single field can be combined into one statement.

1 Like

Thanks RudiC, I love how your brain went there to "trick" CONVFMT and I never knew a carry flag. I have tried your suggestion and it works brilliantly. My input file works in tandem with your suggestion and always will. Many Many thanks.