在 bash 中选择一个具有特定字母数的随机单词

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

我需要随机选择一个 n 个字母的单词,n 将作为参数。

我有这个:

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

所以我知道如何随机选择一个单词,但不知道具体的字母数。

用 3 个字符试试这个:

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

如果你需要一个变量:

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

的解释:

  • ^ : 开始 anchor of line
  • . : 任意字符
  • \{3\} : 最后一个字符的量词
  • $ : 行尾 anchor