I have below given code. I want to print each word and its number of occurrences without using external utils such as wc
, awk
, tr
, etc.
I am able to count the total number of words, but here I have also one issue: in the output I am not getting total word count, the output is less than what it should be.
What should I do?
#!/bin/bash
#v=1
echo -n "ENTER FILE NAME: "
read file
IFS=$'\n'
cnew_line=`echo -e "\n"`
cspace=`echo " "`
if [ $# -ne 0 ]
then
echo "You didn't entered a filename as a parameter"
exit
elif [ $# -eq 0 ]
then
filename="$file"
num_line=0
num_word=0
num_char=0
while read -n1 w
do
if [ "$w" = "$cnew_line" ]
then
(( num_line++ ))
elif [ "$w" = "$cspace" ]
then
(( num_word++ ))
else
(( num_char++ ))
fi
done < "$filename"
echo "Line Number = $num_line"
echo "Word Number = $num_word"
echo "Character Number =$num_char"
fi
enter code here