0

I have one array item1 with entries like

item1=($(cat abc.txt | grep "exam" |sed 's/.*exam//'|sed 's/^ *//g'|cut -d/ -f2))

so in this array i have below entries

abc.raml def.raml xyz.schema check1.json check2.json

now i want check for each item of this array item1, if it is present in another array item2

so i did this using for loop

for i in "${item1[@]}"; do
    for j in "${item2[@]}"; do
      if  [[ $i == $j ]]
        then
                echo "file $i present in both arrays"
      fi
    done
done

so this loop is working fine.. but can we just get a one liner command to check if a particular element is present in another array without using another for loop inside

i tried this but it is not working

for i in "${item1[@]}"; do
  echo ` "${item2[@]}" | grep "$i" `
      if  echo $? == 0
        then
                echo "file $i present in both arrays"
      fi
    done
done

Please help me here

garima
  • 53
  • 1
  • 9

1 Answers1

0

Print both arrays as a sorted list, then with comm extract elements present in both lists.

$ item1=(abc.raml def.raml xyz.schema check1.json check2.json)
$ item2=(abc.raml def.raml xyz.schema check1.json check2.json other)

$ comm -12 <(printf "%s\n" "${item1[@]}" | sort) <(printf "%s\n" "${item2[@]}" | sort) | xargs -I{} echo "file {} present in both arrays"
file abc.raml present in both arrays
file check1.json present in both arrays
file check2.json present in both arrays
file def.raml present in both arrays
file xyz.schema present in both arrays

to check if a particular element is present in another array

Print the array as list and grep the element.

if printf "%s\n" "${item1[@]}" | grep -qxF abc.raml; then
    echo "abc.raml is present in item1"
fi

When working with array items that can have newline in them, use zero separated streams.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111