How to use absolute function?

Hello All,

I am using following awk command in my shell script. I want to compare the value in column 2 and colum 3 after taking their absolute value. Column $2 and $3 can have any value positive or negative or both.

awk -F"|" '{print $0,($2>$3?"F":"T")}' OFS='|' myfile.txt

Your help is appreciated.

Thanks
Angshuman

adopt to your needs...

function abs(v){
  return sqrt(v^2)
}

If myfile.txt contains:

1|1|1
1|-1|1
1|1|-1
1|-1|-1
1|2|3
1|-2|3
1|2|-3
1|-2|-3
1|5|4
1|-5|4
1|5|-4
1|-5|-4

and we change your script to use a more common definition of an absolute value function:

awk -F'|' '
function absolute(arg) {
	return (arg < 0) ? -arg : arg
}
{	print $0, (absolute($2) > absolute($3)) ? "F" : "T"
}' OFS='|'  myfile.txt

the output we get from running the script is:

1|1|1|T
1|-1|1|T
1|1|-1|T
1|-1|-1|T
1|2|3|T
1|-2|3|T
1|2|-3|T
1|-2|-3|T
1|5|4|F
1|-5|4|F
1|5|-4|F
1|-5|-4|F

The added field in this case is F if the absolute value of field 2 is greater than the absolute value of field 3; otherwise it is T .

1 Like