I’m trying to write an AWK script that would check if there are any prime numbers in a file and print them. Here is my code:
#!/bin/awk -f
function is_prime(n) {
if (n <= 1) return 0;
if (n == 2) return 1;
for (i = 2; i <= sqrt(n); i++) {
if (n % i == 0) {
return 0;
}
}
return 1;
}
{
gsub(/[^[:digit:]]/, " ");
for (i = 1; i <= NF; i++) {
if (is_prime($i)) {
print $i;
}
}
}
i executed with a file containing the following text:
Math is179day foun193dary
18
nachum17
19
It should print:
179
193
17
19
but it rather prints:
14
5
5
What is wrong with my code please?
edit: I would like to add that if replace the ‘print i’ line with ‘print $i’ then execute the script, no numbers are printed but only 3 blank lines.
2
Answers
Your
is_prime
function code is alright, however problem is use of variablei
inside the function and outside without letting function know thati
is local. You can bypass this problem by declaring an additional argument in function signature and preserve original value ofi
outside.Read: How to make a variable local to a function
You may use this
awk
script:It seems the problem is related with reusing variable "i" in function is_prime and main. Try to rename it, in the function is_prime(), for example. In my case has resolved.