Find all words containing characters in UNIX

后端 未结 6 1050
误落风尘
误落风尘 2021-02-14 15:18

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\").

He

6条回答
  •  不要未来只要你来
    2021-02-14 15:38

    You want to find words containing only a given set of characters. A regex for that would be:

    '^[letters_you_care_about]*$'
    

    So, you could do:

    grep "^[$W]*$" /usr/dict/words
    

    The '^' matches the beginning of the line; '$' is for the end of the line. This means we must have an exact match, not just a partial match (e.g. "table").

    '[' and ']' are used to define a group of possible characters allowed in one character space of the input file. We use this to find words in /usr/dict/word that only contain the characters in $W.

    The '*' repeats the previous character (the '[...]' rule), which says to find a word of any length, where all the characters are in $W.

提交回复
热议问题