2005-03-21 13:51:11 +00:00
|
|
|
#!/bin/bash
|
2003-11-03 16:26:45 +00:00
|
|
|
# letter-count.sh: Counting letter occurrences in a text file.
|
2005-03-21 13:51:11 +00:00
|
|
|
# Written by Stefano Palmeri.
|
|
|
|
# Used in ABS Guide with permission.
|
|
|
|
# Slightly modified by document author.
|
2003-11-03 16:26:45 +00:00
|
|
|
|
2005-03-21 13:51:11 +00:00
|
|
|
MINARGS=2 # Script requires at least two arguments.
|
|
|
|
E_BADARGS=65
|
|
|
|
FILE=$1
|
2003-11-03 16:26:45 +00:00
|
|
|
|
2005-03-21 13:51:11 +00:00
|
|
|
let LETTERS=$#-1 # How many letters specified (as command-line args).
|
2008-11-23 22:43:47 +00:00
|
|
|
# (Subtract 1 from number of command-line args.)
|
2003-11-03 16:26:45 +00:00
|
|
|
|
|
|
|
|
2005-03-21 13:51:11 +00:00
|
|
|
show_help(){
|
|
|
|
echo
|
|
|
|
echo Usage: `basename $0` file letters
|
|
|
|
echo Note: `basename $0` arguments are case sensitive.
|
|
|
|
echo Example: `basename $0` foobar.txt G n U L i N U x.
|
|
|
|
echo
|
2003-11-03 16:26:45 +00:00
|
|
|
}
|
|
|
|
|
2005-03-21 13:51:11 +00:00
|
|
|
# Checks number of arguments.
|
|
|
|
if [ $# -lt $MINARGS ]; then
|
|
|
|
echo
|
|
|
|
echo "Not enough arguments."
|
|
|
|
echo
|
|
|
|
show_help
|
|
|
|
exit $E_BADARGS
|
|
|
|
fi
|
|
|
|
|
|
|
|
|
|
|
|
# Checks if file exists.
|
|
|
|
if [ ! -f $FILE ]; then
|
|
|
|
echo "File \"$FILE\" does not exist."
|
|
|
|
exit $E_BADARGS
|
|
|
|
fi
|
|
|
|
|
2003-11-03 16:26:45 +00:00
|
|
|
|
2005-03-21 13:51:11 +00:00
|
|
|
|
|
|
|
# Counts letter occurrences .
|
|
|
|
for n in `seq $LETTERS`; do
|
|
|
|
shift
|
|
|
|
if [[ `echo -n "$1" | wc -c` -eq 1 ]]; then # Checks arg.
|
|
|
|
echo "$1" -\> `cat $FILE | tr -cd "$1" | wc -c` # Counting.
|
|
|
|
else
|
|
|
|
echo "$1 is not a single char."
|
|
|
|
fi
|
|
|
|
done
|
2003-11-03 16:26:45 +00:00
|
|
|
|
|
|
|
exit $?
|
2005-03-21 13:51:11 +00:00
|
|
|
|
|
|
|
# This script has exactly the same functionality as letter-count2.sh,
|
|
|
|
#+ but executes faster.
|
|
|
|
# Why?
|