Another.Chemist
Another.Chemist

Reputation: 2559

In bash, How do I test if a word is not in a list?

Good day everybody,

I want to make an if conditional with the following aim:

have two files, the script check a word of file1 (locate in variable $word2test) if exits in file2 (each word locate in variable $wordINlist) do nothing | if the word is not in file2, print it to stdout

My first approach is:

if ! [[ "$word2test" =~ "$wordINlist" ]] ; then
    echo $word2test
fi

Thanks in advance for any suggestion

Upvotes: 2

Views: 2719

Answers (3)

Gilles Quénot
Gilles Quénot

Reputation: 185171

Try this simple bash sample script :

word=foobar
grep -q "\<$word\>" FILE || echo "$word is *not* in FILE"

Another way with REGEX :

word=foobar
grep -q "^$word *$" FILE || echo "$word is *not* in FILE"

Upvotes: 3

Tim Pote
Tim Pote

Reputation: 28029

Assuming $wordINlist is an array (you say "list" but I'm assuming you meant array), you can iterate through it like so:

for item in ${wordINlist[@]}; do
  [[ $item == $word2test ]] || echo $word2test
done

If $wordINlist is a file, then you can simply grep through it:

egrep -q "\b${word2test}\b" "$wordINlist" || echo "$word2test"

When egrep finds a match it returns true, otherwise it returns false. So that simply says, "either a match was found, or echo $word2test"

If all you're wanting to do is see which items are in file1 and NOT in file2, use comm:

comm -23 <(sort -u file1) <(sort -u file2)

Upvotes: 1

Dennis Williamson
Dennis Williamson

Reputation: 360103

If your files are simple lists of one word per line, try this:

grep -Fvf file2 file1

or

join -v 1 <(sort file1) <(sort file2)

Upvotes: 1

Related Questions