I am trying to write a shell script that counts the number of occurrences of a string in a file and take some action based on it.

Here is my script:

if [ grep "\s*oplocks\s=" sample.txt | wc -l = 5 ]
    echo "cnt equals 5"
    echo "cnt not 5"

Along with grep, I also want to count the number of occurrences so I am using wc -l. How can I put this in a if statement?

Thanks for your help!

  • 2
    Do you want to count all occurrences or only count lines that contain the pattern? That is, if a line has the pattern twice should it count once or twice? If the former then you can use grep -o pattern file | wc -l – B Layer Nov 3 '17 at 19:35
  • Just to avoid any confusion when I say "former" in my last comment I'm referring to the first sentence (i.e. "to count all occurrences"). – B Layer Nov 3 '17 at 19:44
  • If a line has multiple occurrences, then I want it to be counted once. – SyncMaster Nov 3 '17 at 20:01
  • In that case you should use grep -c pattern file (no need for wc) as another user suggested .. until I scared them into deleting their answer with my lines vs occurrences query. "Sorry" to whoever that was. :) – B Layer Nov 3 '17 at 20:43

Use command substitution $() and -eq: arithmetic comparison:

if [ $(grep 'something' file | wc -l) -eq 5 ]
       echo equal
       echo not equal

Use the -c argument to grep and skip wc altogether. Also, you can use an arithmetic context to avoid -eq and the like.


if (( $(grep -c 'pattern' sample.txt) == 5 )); then
    echo "5 occurances"


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.