[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: simple grep command twister

On Tue, Jul 18, 2000 at 03:39:47AM +0000, john smith wrote:
> Hi!
>   mind twister break?
> how to use grep to show all the paladrome words in the linux dictionary?
> grep '\(.\)\(.\)\(.\)\3\2\1' \usr\dict\words partly works?

grep can't do it, since wc -L reports that the longest word contains 24
letters and grep can only handle 9 backreferences (so it could only
catch words up to 19 letters long).

Enter perl (:

In the interest of speed, we build up an array of fixed-length patterns
instead of using the very slow

  perl -we '$k=24;@p=(-1,0,".");$f=$b="";for($i=1;$i<=$k/2;$i++){$f.="(.)";
  $b="\\$i$b";push @p,"$f$b","$f.$b"}while(<>){$p=$p[length];/^$p$/ and print}
  ' /usr/share/dict/words

If you don't want the single-letter palindromes, get rid of the very
first period.

Since it turns out that the largest palindromic word in
/usr/share/dict/words is only 7 letters long, we can use grep:
  grep '^\(.\?\)\(.\?\)\(.\?\).\?\3\2\1$' /usr/share/dict/words

Get rid of the first \? if you don't want single-letter palindromes.

  finger for GPG public key.

Attachment: pgpz8uM_B4nTw.pgp
Description: PGP signature

Reply to: