Scrabble helper in bash

brace-expansiongrepwildcards

I'm trying to make a scrabble helper in bash, which when given a list of characters, finds all the words in the /usr/share/dict/words file.
For example, when given the letters a,c,r,t
The word cart will match
The word car will also match
The word carat will not match

However, if a,a,c,r,t were given
Then carat would have matched.

I am trying to find if it is possible only using grep, I suspect that brace expansions like
{a,c,r,t}{a,c,r,t} might be useful to generate all the possible combinations of the letters but instead I am greeted with the errors like

grep: aaac: No such file or directory
grep: aaar: No such file or directory
grep: aaat: No such file or directory   

when running the command
$ grep {a,c,r,t}{a,c,r,t}{a,c,r,t}{a,c,r,t} /usr/share/dict/words

When I use quotes like "{a,c,r,t}{a,c,r,t}" or "\{a,c,r,t\}\{a,c,r,t\}", brace expansion does not work at all

I know that the above command should not work as a scrabble helper but the errors are still rather unexpected. What is wrong with the command and how do I fix it? Also, can grep be used some way to make a scrabble helper at all?

Best Answer

Regular expressions are not the best tool for this kind of job. I'd do something like:

perl -CLASD -lne '
  BEGIN{$l0{$_}++ for (split "", shift)}
  %l = %l0; for (split "") {next LINE unless $l{$_}--}
  print' aacrt < /usr/share/dict/words

Or since (at least in French and English and some other languages using the latin alphabet), scrabble only has the 26 uppercase letters A to Z (été is written as ETE, cœur as COEUR), with GNU iconv:

iconv -t us//TRANSLIT < /usr/share/dict/words |
  perl -CLASD -lne '
    BEGIN{$l0{$_}++ for (split "", uc shift)}
    %l = %l0; for (split "", uc $_) {next LINE unless $l{$_}--}
    print' croeu

Or to output in the original form:

perl -CLASD -MText::Unidecode -lne '
  BEGIN{$l0{$_}++ for (split "", uc shift)}
  %l = %l0; for (split "", uc unidecode $_) {next LINE unless $l{$_}--}
  print' croeu < /usr/share/dict/word
Related Question