Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I count the occurrences of a string within a file?

Tags:

bash

search

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  
like image 985
Leo Chan Avatar asked Jul 19 '11 03:07

Leo Chan


People also ask

How do you count the number of occurrences of words in a text file?

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.

How do you count specific occurrences of characters in a string?

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.


1 Answers

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 
like image 116
Dmitry Avatar answered Oct 10 '22 20:10

Dmitry