There is no built-in function in bash to count the total number of uppercase letters and lowercase letters of a string data or in the content of a file. But many options exist in bash to do this task. Three ways of counting the total number of lowercase and uppercase letter in bash have been shown in this tutorial.
Example-1: Count uppercase and lowercase letter using 'awk'
command
Create a bash file with the following script to count the total number of uppercase letters and lowercase letters by using awk
command. The u and l variables have been used in the script to store the total number of uppercase and lowercase letter.
str="Hello Everyone"
#Print the string value
echo " $str"
#Print the total number of uppercase and lower case letters of the string
awk 'BEGIN{ FPAT="[a-zA-Z]"; l=u=0 }
{
for (i=1; i<=NF; i++) ($i~/[a-z]/)? l++ : u++;
printf " Total uppercase: %d\n Total lowercase: %d\n", u, l
}' <<<"$str"
The following output will appear after executing the above script.
Example-2: Count uppercase and lowercase letter of a file using 'gawk'
command
Create a bash file with the following script that will count the total number of uppercase and lowercase letters by using gawk command. The [A-Z] range has been used here to count the uppercase letter and [a-z] range has been used to count the lowercase letter.
#Read the content of the file
while read line; do
echo "$line"
done < indata.txt
#Count the total number of uppercase and lowercase characters of the file
gawk '{
print "Total uppercase:", patsplit($0, a, /[A-Z]/)
print "Total lowercase", patsplit($0, a, /[a-z]/)
}' RS="\0" indata.txt
The following output will appear after executing the above script.
Example-3: Count uppercase and lowercase letter of a string data using 'grep'
command
Create a bash file with the following script that will count the total number of uppercase and lowercase letters by using grep command. The [A-Z] range has been used here to count the uppercase letter and [a-z] range has been used to count the lowercase letter.
str="Hello Everyone"
#Print the string value
echo "$str"
#Print total number of lowercase letters
echo -n "Total lowercase:"
grep -o '[a-z]' <<< "$str" | wc -l
#Print total number of uppercase letters
echo -n "Total uppercase:"
grep -o '[A-Z]' <<< "heLLo" | wc -l
The following output will appear after executing the above script.