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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#!/bin/sh cnt=0 while read line; do IFS=' ' read -a lines <<< "${line}" for i in "${lines[@]}" do vowels=$(echo $i | grep -io [aeiou]|wc -l) if [ "$vowels" > "0" ] then let cnt=cnt+vowels fi done done <vowels.txt echo "$cnt vowels" |
- #!/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.
- 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.
- while read line; do: This starts a loop that reads each line in the file, one at a time.
- 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.
- for word in “${words[@]}”; do: This starts another loop that goes through each word in the words array.
- 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.
- 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.
- let cnt=cnt+vowels: This increments the cnt variable by the number of vowels found in the current word.
- done: This ends the inner for loop.
- done <vowels.txt: This ends the outer while loop and specifies the input file to read from (in this case, vowels.txt).
- 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.
- 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:
1 |
bash countvowels.txt |
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