0

I want to remove the elements of an array which contains the elements of an other array.

EG

array1 = (aaaa bbbb abcd)

array2 = (b c)

result = (aaaa)

I've wrote this piece of code but it doesn't work

for element in "${array2[@]}"
    do
        result=(${array1[@]/.*$element.*})
    done

could you tell me why and what should I do instead?

Community
  • 1
  • 1
Chris Cris
  • 215
  • 3
  • 13

2 Answers2

1

I think you are mistaken that you need comma as a separator between the elements of the array. But the comma actually becomes a part of an element. Other than that, the result won't wok either as you need to aggregate the removed elements. But result is assigned from array1. So the element removed from the previous iteration will again be a part of resut.

array1=(aaaa bbbb abcd)
array2=(b c)   
result=("${array1[@]}")

for element in "${array2[@]}"
do
     result=(${result[@]/*${element}*/})
done

echo "${result[@]}"

This copies the array into result array and removes elements from it using array2.

P.P
  • 117,907
  • 20
  • 175
  • 238
  • I'm sorry, the comma is only a mistake in reporting. There are no commas in the code in which I have the problem. By the way thanks for the tip...I didn't notice it! I'm going to edit and correct my post. – Chris Cris Dec 10 '15 at 10:20
  • I figured that. The issue was also with your substitution. You can see the difference in the answer. You can also work with `array1` itself if you are OK to modify it. – P.P Dec 10 '15 at 10:23
1

Here is my stab at it. I'm pretty sure this could be done completely with awk but I havn't found out how yet:

#!/bin/bash
array1=(aaaa bbbb abcd)
array2=(b c)   
result=()
for i in "${array1[@]}"
do
   sumIndexOf=0
   for j in "${array2[@]}"
   do
        sumIndexOf=$((sumIndexOf + $(echo $i $j | awk '{print index($1,$2)}')))     
   done
   if [ "$sumIndexOf" = "0" ]; then
        result+=($i)
   fi   
done
printf '%s\n' "${result[@]}"

References/Used:

Community
  • 1
  • 1
Menelaos
  • 23,508
  • 18
  • 90
  • 155