Linux – Shell Script Count Vowels from file

To begin with, start by creating a new file called “vowels.txt”. Inside this file, add a few lines of text containing some vowels (a, e, i, o, u).

Next, create another file in the same directory with the name “countvowels.txt”. Then, copy and paste the following code:

  1. #!/bin/sh: This is a shebang statement that tells the shell which interpreter to use for executing this script. In this case, it uses the Bourne shell.
  2. cnt=0: This initializes a variable called cnt to zero, which will be used to keep track of the total number of vowels found in the file.
  3. while read line; do: This starts a loop that reads each line in the file, one at a time.
  4. IFS=’ ‘ read -a words <<< “${line}”: This splits the line into an array of words, with each word separated by a space. The IFS (Internal Field Separator) variable is set to a space, which tells the shell to use spaces as the delimiter when splitting the line. The read command reads the line and stores each word in the array words.
  5. for word in “${words[@]}”; do: This starts another loop that goes through each word in the words array.
  6. vowels=$(echo $word | grep -io [aeiou] | wc -l): This command counts the number of vowels in the current word using the grep command. The -io options tell grep to ignore case and output only the matching parts of the line. The [aeiou] pattern matches any vowel, and the wc -l command counts the number of matches.
  7. if [ “$vowels” -gt “0” ]; then: This conditional statement checks if the word contains at least one vowel. If so, it executes the following line(s) of code.
  8. let cnt=cnt+vowels: This increments the cnt variable by the number of vowels found in the current word.
  9. done: This ends the inner for loop.
  10. done <vowels.txt: This ends the outer while loop and specifies the input file to read from (in this case, vowels.txt).
  11. echo “$cnt vowels”: This displays the total number of vowels found in the file. The $cnt variable is expanded to its value, and the string “vowels” is added to the end.
  12. This shell script uses a while loop to read each line in the “vowels.txt” file and then splits each line into individual words. It then loops through each word and counts the number of vowels using the grep command. If the word contains any vowels, the vowel count is added to the overall count.

Finally, open your terminal (such as Putty) and run the shell script using the command:

This will execute the shell script and display the total number of vowels found in the “vowels.txt” file.

Let us check another article for Linux

Scroll to Top