Just take this code as an example. Pretending it is an HTML/text file, if I would like to know the total number of times that echo
appears, how can I do it using bash?
new_user() { echo "Preparing to add a new user..." sleep 2 adduser # run the adduser program } echo "1. Add user" echo "2. Exit" echo "Enter your choice: " read choice case $choice in 1) new_user # call the new_user() function ;; *) exit ;; esac
To count the number of occurrences of a specific word in a text file, read the content of text file to a string and use String. count() function with the word passed as argument to the count() function.
First, we split the string by spaces in a. Then, take a variable count = 0 and in every true condition we increment the count by 1. Now run a loop at 0 to length of string and check if our string is equal to the word.
The number of string occurrences (not lines) can be obtained using grep
with -o
option and wc
(word count):
$ echo "echo 1234 echo" | grep -o echo echo echo $ echo "echo 1234 echo" | grep -o echo | wc -l 2
So the full solution for your problem would look like this:
$ grep -o "echo" FILE | wc -l
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With