jhon.smith
jhon.smith

Reputation: 2043

Unix shell sh get items from setA that are missing in SetB

I am using sh Shell (legacy requirements) I have a set like this

Set A --> 'A.txt B.txt C.txt D.txt E.txt' 
and another set like 
Set B --> 'A.txt D.txt'

If i want to find the items that is present in set B but not in set A

setA='A.txt B.txt C.txt D.txt E.txt'
setB='A.txt D.txt'

echo $setA |grep -v -w $setB

My attempt does not yeild any results at all

Upvotes: 0

Views: 34

Answers (1)

oliv
oliv

Reputation: 13249

You can try the following:

for i in $setB; do 
  if ! echo "$setA" | grep -q "$i";  then 
    echo "$i is not in setA"
  fi
done

If you have bash, you could try this:

for i in $setB; do [[ "$setA" =~ "$i" ]] || echo "$i is not in setA"; done

The operator =~ is used to check if an element of setB is part of setA.

Given the 2 sets, there is no match because you asked items that are present in set B but not in set A.

If you extend the setB with another element like this:

setB='A.txt D.txt F.txt'

and then you get

$ for i in $setB; do [[ "$setA" =~ "$i" ]] || echo "$i is not in setA"; done
F.txt is not in setA

Upvotes: 1

Related Questions