You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shell脚本问题:如何精准输出指定$len数量的随机单词?

Hey there! Let's tackle why your shell script isn't reliably outputting exactly $len words every time. From what you described, the shuffle works fine, so the issue is likely with how you're splitting, filtering, or selecting the words from your input file.

First, let's look at your input text:

getting and picking the and picking the daisies picking the daisies when the daisies when suddenly daisies when suddenly a

If your script is splitting words with something like tr ' ' '\n', consecutive spaces (or leading/trailing spaces in the file) would create empty lines. When you shuffle and take the first $len lines, you might end up grabbing those empty lines instead of actual words—resulting in fewer words than expected.

Fix 1: No-replacement random selection (each word is unique in the output, if available)

This version cleans up the input to eliminate empty lines, then shuffles and picks exactly $len words:

len=4

# First, validate len isn't larger than total words
total_words=$(tr -s ' ' '\n' < words.txt | grep -v '^$' | wc -l)
if [ "$len" -gt "$total_words" ]; then
    echo "Error: Requested $len words, but only $total_words exist in the file"
    exit 1
fi

# Process the file: split words, remove empties, shuffle, pick len, join with spaces
tr -s ' ' '\n' < words.txt | grep -v '^$' | shuf | head -n "$len" | paste -sd ' ' -

Breakdown of each step:

  • tr -s ' ' '\n': Collapses multiple spaces into a single newline, so each word is on its own line (no duplicates from extra spaces)
  • grep -v '^$': Filters out any empty lines (from leading/trailing spaces)
  • shuf: Randomizes the list of words
  • head -n "$len": Grabs exactly the first $len words from the shuffled list
  • paste -sd ' ' -: Joins the selected words into a single space-separated line (no trailing space)

Fix 2: With-replacement random selection (allow repeated words)

If you want to allow the same word to appear multiple times in the output (like picking from a bag with replacement), use an array to store the words and randomly select $len times:

len=4

# Load all valid words into an array
words=($(tr -s ' ' '\n' < words.txt | grep -v '^$'))
total_words=${#words[@]}

if [ "$len" -gt 0 ] && [ "$total_words" -eq 0 ]; then
    echo "Error: No words found in the file"
    exit 1
fi

# Build the result by picking random words $len times
result=()
for ((i=0; i<len; i++)); do
    # Generate a random index between 0 and total_words-1
    random_idx=$((RANDOM % total_words))
    result+=("${words[$random_idx]}")
done

# Output the final string
echo "${result[*]}"

This method guarantees you'll get exactly $len words every time, even if you request more than the number of unique words in the file.

内容的提问来源于stack exchange,提问作者Anon_Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:17:11