1

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:

#!/bin/sh
if [ grep "\s*oplocks\s=" sample.txt | wc -l = 5 ]
then
    echo "cnt equals 5"
else
    echo "cnt not 5"
fi

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
1

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

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

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

#!/bin/bash

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

exit

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.