Проверьте, содержит ли строка элемент массива с помощью сценария оболочки - PullRequest
1 голос
/ 31 января 2020

У меня есть массив, содержащий различные подстроки

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 "

Я хочу проверить, используя bash, если текст содержит все строки, которые находятся внутри массива, но по-другому, в данный момент я могу получить их вот так

if [[ $text == *${array[0]}* && $text == *${array[1]}* && $text == *${array[2]}* && $text == *${array[3]}* && $text == *${array[4]}* && $text == *${array[5]}*  ]]; then
  echo "It's there!"
fi

Ответы [ 3 ]

2 голосов
/ 31 января 2020

Более многоразовый способ:

#!/usr/bin/env bash

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 "

check(){
    local str string=" $1 "; shift
    MAPFILE=()
    for str; do
        pattern="\b$str\b" # Word search, excluding [Jacky], for example
        [[ $string =~ $pattern ]] || MAPFILE+=($str)
    done
    test ${#MAPFILE[@]} = 0
}

if  check "$text" "${array[@]}"; then
    echo "All in"
else
    echo "Not all in : [${MAPFILE[@]}]"
fi
1 голос
/ 31 января 2020

Попробуй это. L oop через ваш массив и мач $item с $text

array=(Jack Jessy Harold Ronald Boston Naomi Bill Marry)
text=" Jack is maried with Jessy, they have 3 children Ronald Boston and Naomi and Harold is the last one "

$ for item in ${array[@]}; { [[ "$text" =~ $item ]] && echo yep $item is here || echo nop can\'t find $item; }
yep Jack is here
yep Jessy is here
yep Harold is here
yep Ronald is here
yep Boston is here
yep Naomi is here
nop can't find Bill
nop can't find Marry

Обновление, чтобы суммировать результаты

err=0; for item in ${array[@]}; { [[ "$text" =~ $item ]] || ((err++)); }; ((err>0)) && echo someone is missing || echo all there

Или так, чтобы увидеть, кого не хватает

for item in ${array[@]}; { [[ "$text" =~ $item ]] || missing+=($item); }; [[ ${missing[@]} ]] && echo can\'t find ${missing[@]} || echo all there
0 голосов
/ 31 января 2020

Оболочка - это среда для вызова инструментов, а не инструмент для манипулирования текстом. Ребята, которые изобрели 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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...