Home > database >  how to write awk code with specific condition
how to write awk code with specific condition

Time:02-24

I want to create a code that operates on a certain number of a row of data, for which I just want to count negative numbers to make them positive by multiplying by the number itself negative example

data

10
11
-12
-13
-14

expected output

10
11
144
169
196

this is what I've been try

awk 'int($0)<0 {$4 = int($0)   360} 
     END {print $4}' data.txt

but I don't even get the output, anyone can help me?

CodePudding user response:

awk '$0 < 0 { $0 = $0 * $0 } 1' data.txt

The first condition multiplies the value by itself when it's negative. The condition 1 is always true, so the line is printed unconditionally.

CodePudding user response:

Also:

awk '{print($0<0)?$0*$0:$0}' input

CodePudding user response:

You could also match only digits that start with - and in that case multiply them by themselves

awk '/^-[[:digit:]] $/ {print $0 * $0; next}1' file
  • Related