2

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.

5
  • Possible duplicate of bash: how to delete elements from an array based on a pattern Commented Feb 29, 2016 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... Commented Feb 29, 2016 at 21:31
  • Did you look at the answers? Like, this one: stackoverflow.com/a/31125399/1255289 Commented Feb 29, 2016 at 21:35
  • 1
    With GNU bash 4: declare -l -a array=(ABC DEF GHI); declare -p array and help declare Commented Feb 29, 2016 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 Commented Feb 29, 2016 at 21:46

1 Answer 1

2

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")'
Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.