我有點堅持這個如何檢查我的文本中應該存在的所有關鍵字
如果任何一個關鍵字不存在,那么它應該回傳我狀態: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 $?
uj5u.com熱心網友回復:
shell這是使用and實作此目的的另一種方法grep:
diffSets() {
[[ -n $2 && -z $( grep -vxFf <(echo "${1// /$'\n'}") <(echo "${2//|/$'\n'}") ) ]]
}
此函式首先用第一組中的換行符替換所有空格,并在第二組中用換行符替換所有管道。然后它使用行程替換grep -vxFf來使用第一組作為搜索模式從第二組中獲取不匹配的文本。
測驗:
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
uj5u.com熱心網友回復:
使用您顯示的示例和嘗試,請嘗試以下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.
}
}
'
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/482066.html
