pogibas
pogibas

Reputation: 28339

awk math: check result before printing

My input is:

cat input  
   1  
   4  
  -2

I want to subtract some value (e.g., 2) from column 1. If result is > 0 print it or else print 0. In other words, I don't want any negative numbers.

My try is:

 awk '{NUMBER=$1-2} if (NUMBER > 0) print NUMBER; else print 0'  

But I am probably making some syntax mistake.

Wanted ouput is:

0
2
0

Upvotes: 0

Views: 96

Answers (2)

Ed Morton
Ed Morton

Reputation: 203393

With this:

awk '{NUMBER=$1-2} if (NUMBER > 0) print NUMBER; else print 0'

you're putting the if... statement in the condition part of the awk body instead of the action part because it's not enclosed in curly brackets. This is the correct syntax for what you wrote:

awk '{NUMBER=$1-2; if (NUMBER > 0) print NUMBER; else print 0}'

but in reality I'd write it as:

awk '{NUMBER=$1-2; print (NUMBER > 0 ? NUMBER : 0)}'

Upvotes: 2

fedorqui
fedorqui

Reputation: 289645

This can be an option:

$ awk '{$1=$1-2>0?$1-2:0; print $1}' file
0
2
0

$1=$1-2>0?$1-2:0 is a ternary operator and is read like this:

Set $1 to:

    if ($1-2 > 0)
         ==> $1-2
    else ==> 0

and then it is printed out print $1.

Upvotes: 3

Related Questions