Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

What Unix command(s) can I use to determine the existence of each of several words and the non-existence of each of several words which will produce a binary answer?

For example: I want to be sure that a file has the word "foo" listed 6 times and "bar" listed 8 times. I also want to be sure that the file has neither "fizz" nor any "buzz"

share|improve this question
up vote 1 down vote accepted

There may be more elegent ways to do this, but this will do the trick, for a file called test:

if [ `grep -c bar test` == 8 ] && [ `grep -c foo test` == 6 ] && [ `grep -c fizz test` == 0 ] && [ `grep -c buzz test` == 0 ] ; then  echo "yes" ; else echo "no" ; fi
share|improve this answer
This will fail when words appear multiple times on the same rows, since grep -c only returns number of matching rows, not word counts. echo "test test" | grep -c test will return 1. – Daniel Andersson Jun 13 '12 at 5:42
@DanielAndersson Good point Ocasta, can you add more information about the data structure to your question? – Paul Jun 13 '12 at 5:48
@Paul, I'm trying to build a sanity check for a derived text file. It may be that the same word appears multiple times on each line but if my understanding of how this particular text file is built is correct then it is a safe bet that the file is sane if each of the words are mentioned at least once. – Ocasta Eshu Jun 25 '12 at 2:13
So I guess a more relevant question would be how do I get a binary response if foo and bar exist an unknown number of times (i just want to be sure they are in the file)? – Ocasta Eshu Jun 25 '12 at 2:36
Changing the if to if [ grep -c bar test -gt 0 ] && [ grep -c foo test -gt 0 ]` would probably do it... – Paul Jun 25 '12 at 3:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .