如何检查给定文本中是否应存在所有多个关键字

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

我对此有点困惑,如何检查我的文本中是否应存在所有关键字

如果任何一个关键字不存在,那么它应该 return me status : 1 否则 0

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

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

我的代码:

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

根据您展示的示例和尝试,请尝试遵循 awk 代码。在 GNU awk 中编写和测试,应该在 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
  }
}
'

说明:为以上代码添加详细说明。

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.
  }
}
'

这是使用 shellgrep 实现此目的的另一种方法:

diffSets() {
   [[ -n  && -z $( grep -vxFf <(echo "${1// /$'\n'}") <(echo "${2//|/$'\n'}") ) ]]
}

此函数首先在第一组中用换行符替换所有空格,在第二组中用换行符替换所有管道。然后它使用 grep -vxFf 的进程替换从第二组中获取 not-matching 文本,使用第一组作为搜索模式。

测试:

keyword='CAP|BALL|BAT|CRICKET'
s="HE AS CAP AND LOVE TO PLAY BALL BAT , ITS IS CALLED CRICKET"

diffSets "$s" "$keyword" && echo "all" || echo "not all"
all

keywork='CAP|BALL|BAT|CRICKET|FOO'
diffSets "$s" "$keywork" && echo "all" || echo "not all"
not all

diffSets "$s" "" && echo "all" || echo "not all"
not all