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.

5
  • What did you try? Commented Mar 26, 2020 at 10:57
  • @Inian I took help from some of the other array comparisons related questions, but couldn't able to achieve what I intended. Commented Mar 26, 2020 at 11:06
  • can the actual array contents contains spaces?. Also post whatever half efforts you made so far. Commented Mar 26, 2020 at 11:06
  • Did you look at Compare/Difference of two arrays in bash Commented Mar 26, 2020 at 11:08
  • Yes @Inian I referred this. Was helpful Commented Mar 26, 2020 at 11:26

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.