Оболочка - это среда для вызова инструментов, а не инструмент для манипулирования текстом. Ребята, которые изобрели shell, также изобрели awk для shell, чтобы вызывать для манипулирования текстом. Приведенный ниже скрипт awk будет работать четко, надежно, эффективно и переносимо, используя любой awk в любой оболочке на каждом UNIX поле:
$ cat tst.sh
#!/bin/env bash
checkWordsInSentence() {
awk -v wordsStr="${array[*]}" -v sentenceStr="$text" 'BEGIN {
split(sentenceStr,words,/[^[:alpha:]]+/)
for (i in words) {
sentence[words[i]]
}
split(wordsStr,words)
for (i in words) {
word = words[i]
totWords++
if (word in sentence) {
status[word] = "present"
numPresent++
}
else {
status[word] = "absent"
}
}
if (totWords == numPresent) {
printf "All %d words (%s) present\n", totWords, wordsStr
}
else {
printf "%d of %d words (%s) present\n", numPresent, totWords, wordsStr
for (word in status) {
print word, status[word]
}
}
}'
}
array=(Jack Jessy Harold Ronald Boston Naomi)
text=" Jack is maried with Jessy, they have 3 children Ronald Boston and Naomi and Harold is the last one "
checkWordsInSentence
echo '----'
array=(Jack Jessy Harold Bob Ronald Boston Naomi Karen)
text=" Jack is maried with Jessy, they have 3 children Ronald Boston and Naomi and Harold is the last one "
checkWordsInSentence
.
$ ./tst.sh
All 6 words (Jack Jessy Harold Ronald Boston Naomi) present
----
6 of 8 words (Jack Jessy Harold Bob Ronald Boston Naomi Karen) present
Karen absent
Ronald present
Bob absent
Jack present
Boston present
Naomi present
Jessy present
Harold present