ZakS
ZakS

Reputation: 1131

Output includes blank line for each condition that was checked using Awk

I have a function that looks at every number in a file, checks if it is a perfect square, and if it is, increments a counter by 1. The goal of the function is to count the total number of perfect squares.

awk 'function root(x)  
{if (sqrt(x) == int(sqrt(x))) count+=1 } 
{print root($1)}
END{print count}' numbers_1k.list

The output from this code gives a blank line for each time it checked the condition on a line of the file. So if the file has 1000 lines, its 1000 blank lines in the output followed by the variable count

Is there anyway to avoid this? I have checked previous similar questions.

Upvotes: 1

Views: 84

Answers (2)

RavinderSingh13
RavinderSingh13

Reputation: 133458

Could you please try following too.

awk 'function root(x)  
{if (sqrt(x) == int(sqrt(x)))
 {print x;count+=1
 } 
}
{root($1)}
END{print "count=",count}'  Input_file

Above code should add variable count whenever there is a TRUE condition found in function and you could increment its value inside function itself, finally you could print it in END block of awk code.

Upvotes: 1

hek2mgl
hek2mgl

Reputation: 157947

The problem is that you use { print root() } where root() doesn't return anything, it should be:

awk 'function root() { return sqrt(x) == int(sqrt(x))}
     root($1) {count++}
     END {print count}' file

Btw, you don't need a function for that:

awk 'sqrt($1) == int(sqrt($1)) {count++} END {print count}' file

Upvotes: 3

Related Questions