Find all words containing characters in UNIX

Posted by fahdshariff on Stack Overflow See other posts from Stack Overflow or by fahdshariff
Published on 2010-03-04T10:19:49Z Indexed on 2010/03/08 0:30 UTC
Read the original article Hit count: 344

Filed under:
|

Given a word W, I want to find all words containing the letters in W from /usr/dict/words. For example, "bat" should return "bat" and "tab" (but not "table").

Here is one solution which involves sorting the input word and matching:

word=$1
sortedWord=`echo $word | grep -o . | sort | tr -d '\n'`

while read line
do
    sortedLine=`echo $line | grep -o . | sort | tr -d '\n'`
    if [ "$sortedWord" == "$sortedLine" ]
    then
        echo $line
    fi
done < /usr/dict/words

Is there a better way? I'd prefer using basic commands (instead of perl/awk etc), but all solutions are welcome!

To clarify, I want to find all permutations of the original word. Addition or deletion of characters is not allowed.

© Stack Overflow or respective owner

Related posts about unix

Related posts about shell-scripting