Home > Software engineering >  How to Grep a string that contains multiple words but check each word individually and exactly?
How to Grep a string that contains multiple words but check each word individually and exactly?

Time:10-30

I am trying to do the following.

I have a file called checker.txt and it contains the following

blue
brown
cat
dog
jumps
over
the
red
yellow
fox
quick
lazy

I have the string the quick brown fox jumps over the lazy dog

And the idea is I want to grep the string into the checker.txt file. And I want to check that each word in "the quick brown fox jumps over the lazy dog" is in the checker.txt file. And return something like a 1 to confirm that all of the words in the string is in the checker.txt file.

I'm really new to grep and don't know if this is even possible.

Any and all help will be really appreciated.

More Information:

I realized you could do something like this which is allows you to search multiple words exactly in a file like:

grep -w 'the$\|quick$\|brown$' checker.txt

And it returns all the words that match exactly.

However that means changing the original string into a different form. Which I can do but I want to find if there is an alternative that is simpler and easier than having to parse it.

CodePudding user response:

Given these two files:

cat checker.txt
blue
brown
cat
dog
jumps
over
the
red
yellow
fox
quick
lazy

cat file
the quick brown fox jumps over the lazy dog

It is easier in something like awk:

awk 'FNR==NR{check[$1]; next}     # read the checker file
                                  # next file
     {for (i=1;i<=NF;i  )         # for each field in line    
         if (!($i in check)) next} # skip printing if word
                                  # not in check file
     1 ' checker.txt file         # 1 mean 'print' in this case
  • Related