Shell script to find a word frequency

Shell Scripting

Below shell script to find a word frequency can be used to find frequency of occurrence of word or words in a file.

#!/bin/bash
#Name: wfreq.sh
#Description: Find out frequency of words in a file
if [ $# -ne 1 ];
then
echo "Usage: $0 filename";
exit -1
fi
filename=$1
egrep -o "\b[[:alpha:]]+\b" $filename | \
awk '{ count[$0]++ }
END{ printf("%-14s%s\n","Word","Count") ;
for(ind in count)
{ printf("%-14s%d\n",ind,count[ind]); }
}'

$ ./wfreq.sh words.txt
Word Count
used 1
this 2
counting 1

In case of any ©Copyright or missing credits issue please check CopyRights page for faster resolutions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.