从数组中删除某些字符串

时间:2016-02-29 21:24:37

标签: arrays bash

下午好,

我遇到了一些问题,如果它们与我的程序中的条件匹配,那么确切地说如何从数组中删除项目列表。示例如下。我想删除任何包含 admin 的内容,无论大小写,以及名单列表中的任何内容。

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

如果需要更长的解释,请告诉我。谢谢。

1 个答案:

答案 0 :(得分:1)

假设您没有数组元素中的换行符,可以使用grep来删除数组条目:

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

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

检查输出:

declare -p sarr
declare -a sarr='([0]="user01" [1]="user02" [2]="user03" [3]="user04" [4]="user09")'