user8887707
user8887707

Reputation:

Picking a random word with an specific number of letters in bash

I need to pick a random word with n letters, n will be the parameter.

I have this:

#!bin/bash
shuf -n1 /usr/share/dict/words

So I know how to pick a random word but not with a specific number of letters.

Upvotes: 1

Views: 874

Answers (1)

Gilles Quénot
Gilles Quénot

Reputation: 185106

Try this for words with 3 characters :

grep '^.\{3\}$' /usr/share/dict/words | shuf -n1

If you need a variable :

num=3
grep "^.\{$num\}\$"  

Explanations of the :

  • ^ : start anchor of line
  • . : any character
  • \{3\} : quantifier of the last character
  • $ : end of line anchor

Upvotes: 3

Related Questions