1

Good afternoon,

I am having some issues figuring out exactly how to remove a list of items from an array if they match my criteria inside of my program. Example is below. I want to remove anything that has admin in it, regardless of case, as well as anything in a list of names.

#This array is a list of user name
declare -a userList=($(command to get users))

#now my userList array is filled with different usernames
#ex = user01 user02 user03 admin user04 Admin_user AdMiN-account user09
#I have a second list of names that I want to remove from the array stored in a variable. Pseudocode is below. test.txt contains **user01 and user02**

for i in ${exclude} ; do
remove name from array
done
code to remove any spelling of admin from userList array.

If a longer explanation is needed please let me know. Thank you.

IT_User
  • 729
  • 9
  • 27
  • Possible duplicate of [bash: how to delete elements from an array based on a pattern](http://stackoverflow.com/questions/3578584/bash-how-to-delete-elements-from-an-array-based-on-a-pattern) – miken32 Feb 29 '16 at 21:28
  • Yes I have looked at that one. Does not explain how to disregard case and shows how to remove a single item such as **pref** instead of removing all items from another array or file... – IT_User Feb 29 '16 at 21:31
  • Did you look at the answers? Like, this one: http://stackoverflow.com/a/31125399/1255289 – miken32 Feb 29 '16 at 21:35
  • 1
    With GNU bash 4: `declare -l -a array=(ABC DEF GHI); declare -p array` and `help declare` – Cyrus Feb 29 '16 at 21:36
  • Yes I did Mike. His answer he shows how to take inside of a function to remove it from an array. I tried to implement something along his lines but was unable to get it to work for my situation – IT_User Feb 29 '16 at 21:46

1 Answers1

1

Assuming you don't have newline in array elements, you can use grep for case-ignore removal of array entries:

arr=(user01 user02 user03 admin user04 Admin_user AdMiN-account user09)

sarr=($(grep -iv 'admin' <(printf "%s\n" "${arr[@]}")))

Check output:

declare -p sarr
declare -a sarr='([0]="user01" [1]="user02" [2]="user03" [3]="user04" [4]="user09")'
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    Thank you very much, I did not even think of something as simple as grep for this case. Perfect answer on the removing admin. Thank you!. – IT_User Feb 29 '16 at 21:47