Eric Bryant
Eric Bryant

Reputation: 11

Compare a string to all elements in an array?

I know there is probably a way to do this but the majority of the ways to do this were the opposite way of what i am trying to accomplish. I want to compare elements in an array (English dictionary words from "words" program), and see if they are contained anywhere in a string. for example if i type in 123hello456, it will scan my string against the array and find hello within that string even tho it is surrounded by numbers.

read -p "enter test string: " string
array=(`cat /usr/share/dict/words`)
if [[ "${array[*]}" == *"$string"* ]]; then
echo "there is a dictionary word in your string"
else
echo "no dictionary words contained within your string"
fi

Upvotes: 1

Views: 1602

Answers (2)

codeforester
codeforester

Reputation: 42999

You can use printf and grep:

if printf '%s\n' "${array[@]}" | grep -qFx -- "$string"; then
  : match found
fi
  • -F matches the content as strings, not patterns
  • -x matches the whole line to prevent false positives arising out of partial matches
  • -q suppresses output
  • -- prevents issues caused by a leading - in $string

Upvotes: 1

dimo414
dimo414

Reputation: 48814

One simple option would be to use grep, which allows you to specify multiple patterns to match, and also to use fixed strings (rather than regular expressions) to avoid that overhead.

$ grep -F -f /usr/share/dict/words <<<'123hello456'
123hello456

This actually matches "ello" since that comes earlier in my words file, but it'd match "hello" too.

You can use the -q flag to suppress grep's output, so your script would become:

read -p "enter test string: " string
if grep -q -F -f /usr/share/dict/words <<<"$string"; then
  echo "there is a dictionary word in your string"
else
  echo "no dictionary words contained within your string"
fi

Note this isn't terribly efficient if you're calling this often, since grep has to re-load the whole words file every time. Depending on what else you're trying to accomplish I'd definitely consider swapping to a "real" language such as Python for a task like this.

Upvotes: -1

Related Questions