# Awk is missing ABS - absolute value - so we have to make it.

# if you want to do:
y=abs(x)
# you cant just write the above as abs(x) is a missing function. You have two options (and many more after that)

#------------------------------------------#

# option1: make a quick abs replacement
y=(x<0?-x:x)
# it checks if x is negative with x<0 and if it is, it converts it to positive with -x, if x is already positive it just remains as x

# option2: make the abs function
function abs(value)
{
 return (value<0?-value:value);
}
# or as a oneliner it would look like this:
function abs(value){return (value<0?-value:value);};

#------------------------------------------#

# examples of use of option1:
echo -50 | awk '{x=$1;y=(x<0?-x:x);print y}'
echo 150 | awk '{y=($1<0?-$1:$1);print y}'

# examples of use of option2:
echo -50 | awk 'function abs(value){return (value<0?-value:value);}; {x=$1;y=abs(x);print y;}'
echo 150 | awk 'function abs(value){return (value<0?-value:value);}; {print abs($1);}'

 

Leave a Reply

Your email address will not be published. Required fields are marked *