remonae
remonae

Reputation: 11

how to write awk code with specific condition

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?

Upvotes: 0

Views: 53

Answers (4)

The fourth bird
The fourth bird

Reputation: 163207

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

awk '{print (/^-[0-9]+$/ ? $0 * $0 : $0)}' data.txt

Output

10
11
144
169
196

Upvotes: 0

Ed Morton
Ed Morton

Reputation: 203129

$ awk '{print $0 ^ (/-/ ? 2 : 1)}' file
10
11
144
169
196

Upvotes: 0

William Pursell
William Pursell

Reputation: 212178

Also:

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

Upvotes: 1

Barmar
Barmar

Reputation: 780673

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.

Upvotes: 1

Related Questions