djcev.com

//

Git Repos / dotfiles / bin / words.sh

Last update to this file was on 2024-01-02 at 05:12.

Show words.sh

#!/bin/sh
#
# Copyright (c) 2015-2021, Cameron Vanderzanden. Available under the
# terms of the 2-clause BSD license. Please see the file "LICENSE" in
# the root dir of this repository for more information.
#
#- words.sh 2015/11/09 cev, last updated 2021/12/07.
## Usage: words.sh [-hV] [-n count] [-s seperator] file
##
## Print random words from a file.
## Defaults to 3 words, seperated by whitespace, from /usr/share/dict/words.
##
## -h Show help
## -n Number of words
## -s Seperator character
## -V Print version info
##
#

[ -x $HOME/.local/bin/cev_print.sh ] && . $HOME/.local/bin/cev_print.sh

self="${0##*'/'}"

file="/usr/share/dict/words"
lcount="0"
num="3"
sep=" "

die_filenotfound() {
print_filenotfound "$*"
exit 1
}

die_getword() {
print_self error
printf "%berror in getword(): " "$_norm" >&2
printf "wcount is: %b%s%b\n" "$_high" "$wcount" "$_clear" >&2
exit 1
}

die_invalidwordcount() {
print_self error
printf "%bword count must be a number; it was: " "$_norm" >&2
printf "%b%s%b\n" "$_high" "$@" "$_clear" >&2
exit 1
}

setnum() {
# strip non-digit characters
num="$(printf "%s" "$@" | tr -C -d "[:digit:]")"
[ -z "$num" ] && die_invalidwordcount "$*"
}

getword() {
word=""
while [ -z "$word" ]; do
# random line, the slow and stupid way.
n=$(jot -r 1 1 $lcount)
line="$(head -$n "$file" | tail -1)"
[ -z "$line" ] && continue
wcount="$(printf "%s" "$line" | wc -w)"
if [ $wcount -eq 0 ]; then
continue
elif [ $wcount -eq 1 ]; then
word="$line"
elif [ $wcount -gt 1 ]; then
# random word, the slow and stupid way.
n=$(jot -r 1 1 $wcount)
word="$(printf "%s" "$line" | cut -d' ' -f $n)"
else
die_getword "$wcount"
fi
done
}

while getopts "hn:s:V?" option; do
case $option in
h) print_help && exit ;;
n) setnum "$OPTARG" ;;
s) sep="$OPTARG" ;;
V) print_version && exit ;;
"?") print_help && exit ;;
esac
shift $((OPTIND - 1))
done

if [ $# -ne 0 ]; then
if [ -r "$@" ]; then
file="$@";
else
die_filenotfound "$*"
fi
fi

lcount="$(wc -l "$file")"
lcount=${lcount%$file}
out=""

while [ $num -gt 0 ]; do
getword
[ $num -eq 1 ] && sep=""
out="${out}${word}${sep}"
num=$((num - 1))
done

printf "%s\n" "$out"

Return to the top of this page or return to the overview of this repo.

Log words.sh

Date Commit Message Author + -
2024-01-02 Change from FreeBSD to Linux, other minor changes cev +1 -1
2021-12-13 Expanded redshift background.sh, misc. changes cev +1 -1
2021-12-08 Initial commit. Dotfiles, scripts, basic Makefile. cev +106  

Return to the top of this page or return to the overview of this repo.