How do I use grep to grab prime number output from my factor program?

I have a factor program that runs and outputs to stdout all the prime numbers that are specified in the given paramters, in this case 30000000-31000000.

Command:

factor/factor 30000000-31000000

Sample output:

30999979 = 30999979
30999980 = 2^2 5 11 140909
30999981 = 3 10333327
30999982 = 2 13 19 62753
30999983 = 7 1663 2663
30999984 = 2^4 3 645833
30999985 = 5 29 439 487
30999986 = 2 293 52901
30999987 = 3^2 3444443
30999988 = 2^2 7749997
30999989 = 30999989
30999990 = 2 3 5 7 43 3433
30999991 = 11 2818181
30999992 = 2^3 163 23773
30999993 = 3 17 607843
30999994 = 2 15499997
30999995 = 5 13 79 6037
30999996 = 2^2 3^6 10631
30999997 = 7^3 90379
30999998 = 2 23 151 4463
30999999 = 3 10333333
31000000 = 2^6 5^6 31

How would I use a pipeline and grep to just grab the prime numbers:

factor/factor 30000000-31000000 | grep 

For example Output:

30999979 = 30999979
30999989 = 30999989

Hi,
Try:

factor/factor 30000000-31000000 | grep '^\([0-9]\+\)[^0-9]\+\1$'

EDIT: Another regular expression...

factor/factor 30000000-31000000 | grep -v ' .* .* '

EDIT 2: second regular expression not work in many case as: 49 = 7^2 by example :o
Regards.

Or

factor/factor 30000000-31000000 | awk '$1 == $3'

Or, translating RudiC's awk command to a grep command that produces the same output:

factor/factor 30000000-31000000 | grep '^\([0-9]*\) = \1$'
1 Like

Two more options :

| grep '= [^ ]*$'
| awk NF==3

(but my favourite would be RudiC's approach)
--
Edit as disdeorgue correctly remarked the would not with for square numbers..
So adjusting for that, the first one becomes :

| grep '= [^ ^]*$'

or

| grep '= [0-9]*$'

Hi, Scrutinizer,
As my second solution, this 2 options not work if number is a square ( eg : 49 = 7^2 )...

Regards.

1 Like

@disedorgue, you are right... I didn't stop to think how the factor program would work and only looked at the input file. The first one is still usable, with a bit of adjustment.