Skip to content

Instantly share code, notes, and snippets.

@stevebest
Created January 23, 2013 08:21
Show Gist options
  • Select an option

  • Save stevebest/4603082 to your computer and use it in GitHub Desktop.

Select an option

Save stevebest/4603082 to your computer and use it in GitHub Desktop.
Pick a random word from a dictionary
#! /usr/bin/env bash
WORDFILE="/usr/share/dict/words"
words=$(wc -l $WORDFILE | grep -oP "\d+")
r=$(((RANDOM * 32768 + RANDOM)%$words+1))
sed -n "$r p" $WORDFILE
@VSharapov
Copy link

VSharapov commented Jan 14, 2020

words=$(cat $WORDFILE | wc -l) works identically on Linux and Darwin and is a bit shorter
https://gist.github.com/VSharapov/f4db3f2b8edc27bd8b9e3323e4869fcd#file-randword-sh-L4

Edit: but your version is more performant on Linux ... :

$ time (for i in {1..1000}; do wc -l /usr/share/dict/words | grep -oP "\d+" >/dev/null; done)

real    0m4.039s
user    0m3.121s
sys     0m0.864s
$ time (for i in {1..1000}; do cat /usr/share/dict/words | wc -l >/dev/null; done)

real    0m4.702s
user    0m3.380s
sys     0m1.274s

... and macOS:

$ time (for i in {1..1000}; do wc -l /usr/share/dict/words | grep -o "\d\+" >/dev/null; done)

real    0m6.438s
user    0m3.251s
sys     0m5.916s
$ time (for i in {1..1000}; do cat /usr/share/dict/words | wc -l >/dev/null; done)

real    0m6.416s
user    0m3.345s
sys     0m6.757s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment