In my last article I had shared the steps to set password for GRUB2 to protect your content from being modified by unauthorized person at the time of system boot up. In this article I will share the steps to delete elements of one array from another array in bash. Suppose you have an array which has some content and the same content exists in another array so your end goal is to remove the duplicate elements from the main array in bash. Now here removing duplicate content does not mean we merge both the arrays and keep the unique value, rather we will remove the element already present in the other one.

 

How to delete elements of one array from another array in bash

 

Steps to delete elements of one array from another array in bash

Delete exact match of the element from the array

So I will create an example script which suits our scenario where I have two arrays. Here I wish to delete all the elements available inside array2, from array1

#!/bin/bash
##
# @Description: delete elements of one array from another array in bash
##

array1="111 222 333 444 555 666 777 888 999"
array2="222 444"

for host in ${array2[@]}; do
array1=( "${array1[@]/$host}" )
done

echo "The new list of elements in array1 are: ${array1[@]}"

 

Output:

# /tmp/script.sh
The new list of elements in array1 are: 111 333 555 666 777 888 999

 

Delete element matching a regex from the array

In this example I have two arrays wherein array2 has some elements and I wish to delete all the matching elements as found in array2 from array1. So for this we would need some regex as shown in the example

#!/bin/bash
##
# @Description: delete elements of one array from another array in bash
##

array1=(111 222122 333 4444 555 666 777 888 999)
array2=(222 444)

result=("${array1[@]}")

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

echo "The new list of elements in array1 are: ${result[@]}"

 

Output:

# /tmp/script.sh
The new list of elements in array1 are: 111 333 555 666 777 888 999

 

Lastly I hope the steps from the article to delete elements of one array from another array in bash on Linux was helpful. So, let me know your suggestions and feedback using the comment section.

 

Leave a Reply

Your email address will not be published. Required fields are marked *