Sunday, September 4, 2022

[SOLVED] How to check all multiple keyword should be present in given text or not

Issue

I am bit stuck with this how do I check all keyword should exist in my text

If any one keyword is not present then it should return me status : 1 or else 0

keyword='CAP\|BALL\|BAT\|CRICKET'

echo "HE AS CAP AND LOVE TO PLAY BALL BAT , ITS IS CALLED CRICKET" 

My code :

echo "HE AS CAP AND LOVE TO PLAY BALL BAT , ITS IS CALLED CRICKET" | grep -w "$keyword"
echo $? 

Solution

With your shown samples and attempts, please try following awk code. Written and tested in GNU awk, should work in any version of awk.

keyword='CAP|BALL|BAT|CRICKET'
echo "HE AS CAP AND LOVE TO PLAY BALL BAT , ITS IS CALLED CRICKET" | 
awk -v key="$keyword" '
BEGIN{
  num=split(key,arr,"|")
  for(i=1;i<=num;i++){
    value[arr[i]]
  }
}
{
  count=0
  for(i=1;i<=NF;i++){
    if($i in value){
      count++
    }
  }
  if(length(value)==count){
    exit 0
  }
  else{
    exit 1
  }
}
'

Explanation: Adding detailed explanation for above code.

keyword='CAP|BALL|BAT|CRICKET'                ##Creating keyword shell variable with values.
echo " CAP   |  BALL |  BA |  CRICKET    " |  ##Printing values by echo command and sending output to awk command.
awk -v key="$keyword" '                       ##Starting awk program and creating variable key which has value of keyword in it.
BEGIN{                                        ##Starting BEGIN section of this awk program from here.
  num=split(key,arr,"|")                      ##Splitting key into array arr with delimiter of | and num will have total number of elements that will come in array.
  for(i=1;i<=num;i++){                        ##Running for loop till value of num.
    value[arr[i]]                             ##Creating array value with index of value of arr here.
  }
}
{
  count=0                                     ##Setting count to 0 here.
  for(i=1;i<=NF;i++){                         ##Traversing through all fields here.
    if($i in value){                          ##Checking if current field is present in value.
      count++                                 ##Increasing count with 1 here.
    }
  }
  if(length(value)==count){                   ##Checking if length of value and count is equal then do following:
    exit 0                                    ##Exit from program with status of 0.
  }
  else{                                       ##if all fields are not coming into variable then:
    exit 1                                    ##Exit from program with status of 1.
  }
}
'


Answered By - RavinderSingh13
Answer Checked By - Timothy Miller (WPSolving Admin)