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?

1
  • 1
    Please include the expected and actual result in your question. Commented Dec 10, 2015 at 13:43

2 Answers 2

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.

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

2 Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.