0

I have two sorted arrays list1=( a b c d) list2=( a b d)

Suppose list1 is a constant list and list2 is created during script execution. I want to compare list2 elements with list1 and discard only those values from list2 which are not there in list1.

Example: if list2=(a b d e f), then I should update list2 as list2=(a b)as (d e f) isn't there in list1.

oguz ismail
  • 1
  • 16
  • 47
  • 69
Biswajit Maharana
  • 531
  • 1
  • 8
  • 23

1 Answers1

1
list1=( a b c d)
list2=( a b d)
list2=($(echo ${list1[*]} ${list2[*]} | tr " " "\n" |sort | uniq -d))

echo ${list2[*]}

Here I convert the 2 lists to strings, separate by white space, sort the values and then find duplicates. The duplicates are then reassigned to the list2 array

Orion
  • 477
  • 2
  • 4
  • 13
  • Thanks for this. Is there any way I can find if ```list2``` is having any elements which is not there in ```list1```. For example, let ```list2=( a b e )``` then it should return ```[e]``` or simple Boolean flag sayng ```False``` as ```[e]``` is not there in ```list1``` – Biswajit Maharana Mar 26 '20 at 11:37
  • @BiswajitMaharana, given that your original list2 and new list2 could be same or different, you should be able to determine this boolean flag yourself. Give it a try. – Prasanna Mar 26 '20 at 11:53